我只是在项目中使用Webpack 2来与Angular 4进行交互。Angular 4 with 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的值完全相同。
我有点困惑,为什么你这样做。你声明你“需要加载动态加载脚本(因为它们在每个页面上都不需要)”,尽管为什么不去''System.import(“...”)'在需要脚本,然后在需要时加载组件? – Fizzix
因为这一个组件从Firebase数据库中提取内容(以及需要加载哪些脚本)。 –
您需要在引导应用程序时在索引文件中的脚本标记中执行System.imports。 – Yeysides