推薦:
https://www.sitepoint.com/ultimate-angular-cli-reference/ (angular-cli的詳細指令說明)/*可深入瞭解*/
說明:
angular:https://angular.cn/docs/ts/latest/cli-quickstart.html (說明:介紹angular-cli,如文件的意義,用途,如何安裝)
github :https://github.com/angular/angular-cli (說明:可以瞭解angular-cli的工作原理)
題外:
coreUI(提供樣式的插件):http://coreui.io/docs/getting-started/introduction
---------------------------------------------------------------
angular-cli引用第三方庫轉載自:http://www.cnblogs.com/baiyangcao/archive/2017/03/15/angular-cli-json.html
Angular-Cli中引用第三方庫
最近在學習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
文件加載到前臺頁面,而後就闊以正常使用這些第三方庫了~~~