詳解Angular-Cli中引用第三方庫
最近在學習angular(AngularJS 2),根據(jù)教程使用angular-cli新建項目,然而在添加JQuery和Bootstrap第三方庫時遇到了問題...
初試
我最初的想法是直接將相對路徑寫到index.html即可,如下:
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="external nofollow" /> <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也是相同的問題,這里顯然是路徑不正確,我的項目目錄結(jié)構(gòu)如下:
angular-form/ |- src/ | |- app/ | |- index.html | ... |- node_modules | |- jquery/ | |- bootstrap/ | ...
其中,網(wǎng)站運行時的根目錄是src
目錄,
所以獲取不到與其處在同一目錄的node_modules
目錄下文件也在情理之中...
另辟蹊徑
經(jīng)過亂七八糟的查找...發(fā)現(xiàn)了可以在/.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" ], ... } ]
再次啟動網(wǎng)站,卻連編譯都無法通過...出現(xiàn)如下問題:
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文件中配置的路徑時相對于網(wǎng)站根目錄的路徑, 接著做如下更改:
"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" ], ... } ]
再次運行網(wǎng)站,成功加載~~~
回看來時路
后來了解到,angular-cli的項目使用webpack來將模塊打包, 我們這里配置的scripts
和styles
會被打包成scripts.bundle.js
和styles.bundle.js
文件加載到前臺頁面,而后就可以正常使用這些第三方庫了~~~
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
AngularJS對動態(tài)增加的DOM實現(xiàn)ng-keyup事件示例
這篇文章主要介紹了AngularJS對動態(tài)增加的DOM實現(xiàn)ng-keyup事件示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03詳解Angular-ui-BootStrap組件的解釋以及使用
這篇文章主要介紹了詳解Angular-ui-BootStrap組件的解釋以及使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07學習AngularJs:Directive指令用法(完整版)
這篇文章主要學習AngularJs:Directive指令用法,內(nèi)容很全面,感興趣的小伙伴們可以參考一下2016-04-04angularJS+requireJS實現(xiàn)controller及directive的按需加載示例
本篇文章主要介紹了angularJS+requireJS實現(xiàn)controller及directive的按需加載示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02