最近在學習angular(AngularJS 2),根據教程使用angular-cli新建項目,
然而在添加JQuery和Bootstrap第三方庫時遇到了問題...
初試
我最初的想法是直接將相對路徑寫到index.html
即可,如下:
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css" />
<script type="text/javascript" src="../node_modules/jquery/dist/jquery.min.js"/>
<script type="text/javascript" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"/>
然鵝。。。並不好使,瀏覽器抓包會顯示請求
http://localhost:4200/node_modules/juqery/dist/jquery.min.js
返回404錯誤,
bootstrap也是相同的問題,這里顯然是路徑不正確,我的項目目錄結構如下:
angular-form/
|- src/
| |- app/
| |- index.html
| ...
|- node_modules
| |- jquery/
| |- bootstrap/
| ...
其中,網站運行時的根目錄是src
目錄,
所以獲取不到與其處在同一目錄的node_modules
目錄下文件也在情理之中...
另辟蹊徑
經過亂七八糟的查找...發現了可以在/.angular-cli.json
文件中配置腳本引用,
在其app.scripts
下配置要添加的腳本,
並在app.styles
下配置要添加的樣式文件:
"app": [
{
...
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
...
}
]
再次啟動網站,卻連編譯都無法通過...出現如下問題:
ERROR in multi script-loader!./src/~/jquery/dist/jquery.min.js script-loader!./src/~/bootstrap/dist/js/bootstrap.min.js
Module not found: Error: Can't resolve 'E:\Code\JavaScript\angular2\angular-forms\src\node_modules\jquery\dist\jquery.min.js' in 'E:\Code\JavaScript\angular2\angular-forms'
@ multi script-loader!./src/~/jquery/dist/jquery.min.js script-loader!./src/~/bootstrap/dist/js/bootstrap.min.js
可以看出這里去加載js腳本時尋找的是src/
目錄下的node_modules
目錄,
所以加載失敗。這意味着angular-cli.json
文件中配置的路徑時相對於網站根目錄的路徑,
接着做如下更改:
"app": [
{
...
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
...
}
]
再次運行網站,成功加載~~~
回看來時路
后來了解到,angular-cli的項目使用webpack來將模塊打包,
我們這里配置的scripts
和styles
會被打包成scripts.bundle.js
和styles.bundle.js
文件加載到前台頁面,而后就闊以正常使用這些第三方庫了~~~
參考鏈接:
http://stackoverflow.com/questions/38855891/angular-cli-webpack-how-to-add-or-bundle-external-js-files
https://www.sitepoint.com/ultimate-angular-cli-reference/