Angular 4 与 Webpack 2,动态加载脚本
Angular 4 with Webpack 2, dynamically loading scripts
我只是在项目中使用 Angular 4 和 Webpack 2。
我试图在 ngOnInit 期间加载一些脚本,但 运行 遇到了一些问题。
问题1.)
我的 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`);
当我执行此操作时,所有资产似乎都已加载,但出现以下错误:
Uncaught (in promise): ReferenceError: $ is not defined
$ 应该在 jQuery 文件中定义。为什么 regular-expressions.js 文件不知道 jQuery 已加载?
问题2.)
最终,我需要动态加载脚本(因为并非每个页面都需要它们)。
我有以下代码:
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 + '');
我不明白为什么行为会有所不同。特别是如果传递给 System.import 的值完全相同。
我最终发现这几乎是 webpack 的一个(相当大的)限制。我得到了 tree-shaking 等的想法,但 WebPack 确实应该允许开发人员在运行时加载脚本的选项。
我现在最终使用了这个方法:
这不是最好的,因为它需要应用程序广泛依赖 jQuery。如果 WebPack 人员决定允许开发人员选择一次性加载脚本,我会回去更正它。
我只是在项目中使用 Angular 4 和 Webpack 2。
我试图在 ngOnInit 期间加载一些脚本,但 运行 遇到了一些问题。
问题1.)
我的 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`);
当我执行此操作时,所有资产似乎都已加载,但出现以下错误:
Uncaught (in promise): ReferenceError: $ is not defined
$ 应该在 jQuery 文件中定义。为什么 regular-expressions.js 文件不知道 jQuery 已加载?
问题2.)
最终,我需要动态加载脚本(因为并非每个页面都需要它们)。
我有以下代码:
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 + '');
我不明白为什么行为会有所不同。特别是如果传递给 System.import 的值完全相同。
我最终发现这几乎是 webpack 的一个(相当大的)限制。我得到了 tree-shaking 等的想法,但 WebPack 确实应该允许开发人员在运行时加载脚本的选项。
我现在最终使用了这个方法:
这不是最好的,因为它需要应用程序广泛依赖 jQuery。如果 WebPack 人员决定允许开发人员选择一次性加载脚本,我会回去更正它。