2017-04-19 94 views
3

我只是在项目中使用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的值完全相同。

+0

我有点困惑,为什么你这样做。你声明你“需要加载动态加载脚本(因为它们在每个页面上都不需要)”,尽管为什么不去''System.import(“...”)'在需要脚本,然后在需要时加载组件? – Fizzix

+0

因为这一个组件从Firebase数据库中提取内容(以及需要加载哪些脚本)。 –

+0

您需要在引导应用程序时在索引文件中的脚本标记中执行System.imports。 – Yeysides

回答

3

我最终发现这是一个非常大的webpack限制。我得到了树木摇晃等概念,但WebPack确实应该允许开发人员在运行时加载脚本。

最后我现在用这个方法:https://stackoverflow.com/a/37844389/3389346

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