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来将模块打包,
我们这里配置的scriptsstyles会被打包成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/

posted @ 2017-03-15 15:35  baiyangcao  阅读(8699)  评论(4编辑  收藏  举报