且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 4 with Webpack 2,动态加载脚本

更新时间:2023-12-05 10:31:58

我最终发现这几乎是 webpack 的一个(相当大的)限制.我得到了摇树等的想法,但 WebPack 确实应该允许开发人员在运行时加载脚本的选项.

我现在最终使用了这种方法:https://***.com/a/37844389/3389346>

这不是最大的,因为它需要对 jQuery 的应用程序广泛的依赖.如果 WebPack 人员决定允许开发人员一次性加载脚本的选项,我会回去纠正它.

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.

I ended up figuring out this was pretty much a (pretty big) limitation of webpack. I get the idea of tree-shaking, etc. but WebPack really should allow developers the OPTION of loading a script at runtime.

I ended up using this method now: https://***.com/a/37844389/3389346

This isn't the greatest because it requires an application wide dependence on jQuery. I will go back and correct it if the WebPack folks ever decided to allow developers the option of one-off loading a script.