2017-04-19 77 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人員決定允許開發人員一次性加載腳本,我會回去修改它。