Angular 4 with Webpack 2, dynamic script loading
I'm just doing Angular 4 with Webpack 2 in a project.
I am trying to load some scripts during ngOnInit and am confusing some problems.
Problem 1.)
I have the following code inside 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 seem to be loaded, but I get the error:
Unprepared (in promise): ReferenceError: $ undefined
$ must be defined in jQuery file. Why doesn't the regular-expressions.js file know that jQuery is loaded?
Problem 2.)
Ultimately I need to load dynamically load scripts (since 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 don't understand why there is a difference in behavior. Especially if the value passed to System.import is exactly the same.
source to share
I ended up figuring out that this was a pretty (pretty big) webpack limitation. I get the idea of ββtrees shaking etc, but the WebPack should really allow OPTION developers to load the script at runtime.
I ended up using this method: fooobar.com/questions/117716 / ...
This is not the best, because the application requires a wide dependency on jQuery. I will come back and fix this if WebPack users chose to allow developers the option of one-time download of the script.
source to share