I am just dabbling with Angular 4 with Webpack 2 on a project.
I am attempting to load some scripts during ngOnInit and am running into some problems.
Problem 1.)
I have the following code within my ngOnInit:
System.import(`../../node_modules/jquery/dist/jquery.js`);
System.import(`../../node_modules/jquery-validation/dist/jquery.validate.js`);
System.import(`../../node_modules/jquery-validation/dist/additional-methods.js`);
System.import(`assets/js/regular-expressions.js`);
When i do this, all the assets appear to load but I get an error of:
Uncaught (in promise): ReferenceError: $ is not defined
$ should be defined in the jQuery file. Why is the regular-expressions.js file not aware that jQuery has been loaded?
Problem 2.)
Ultimately, I need to load dynamically load the scripts (as they are not needed on every page).
I have the following code:
let script = 'assets/js/' + scripts[i].replace(/^\/|\/$/g, '');
/* The following two lines output the same exact text to the console */
console.log('assets/js/regular-expressions.js');
console.log('' + script + '');
/* The following hard-coded line works (as in the script is loaded, raising the $ issue mentioned above */
System.import('assets/js/regular-expressions.js');
/* The following line with a variable throws an error of "Cannot find module 'assets/js/regular-expressions.js'." */
System.import('' + script + '');
I am not understanding why there is a difference in behavior. Especially if the value being passed to System.import is exactly the same.
System.import("...")at the top of the components that require the scripts, and then load the component when needed?