详解Angular-Cli中引用第三方库

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

详解Angular-Cli中引用第三方库

baiyangcao   2020-05-15 我要评论

最近在学习angular(AngularJS 2),根据教程使用angular-cli新建项目,然而在添加JQuery和Bootstrap第三方库时遇到了问题...

初试

我最初的想法是直接将相对路径写到index.html即可,如下:

 <link rel="stylesheet" href="../node_modules/bootstraphttps://img.qb5200.com/download-x/dist/css/bootstrap.min.css" rel="external nofollow" />
<script type="text/javascript" src="../node_modules/jqueryhttps://img.qb5200.com/download-x/dist/jquery.min.js"/>
<script type="text/javascript" src="../node_modules/bootstraphttps://img.qb5200.com/download-x/dist/js/bootstrap.min.js"/> 

然鹅。。。并不好使,浏览器抓包会显示请求

 http://localhost:4200/node_modules/juqeryhttps://img.qb5200.com/download-x/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/bootstraphttps://img.qb5200.com/download-x/dist/css/bootstrap.min.css"
  ],
  "scripts": [
   "node_modules/bootstraphttps://img.qb5200.com/download-x/dist/css/bootstrap.min.css",
   "node_modules/bootstraphttps://img.qb5200.com/download-x/dist/css/bootstrap.min.css"
  ],
  ...
 }
] 

再次启动网站,却连编译都无法通过...出现如下问题:

 ERROR in multi script-loader!./src/~/jqueryhttps://img.qb5200.com/download-x/dist/jquery.min.js script-loader!./src/~/bootstraphttps://img.qb5200.com/download-x/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/~/jqueryhttps://img.qb5200.com/download-x/dist/jquery.min.js script-loader!./src/~/bootstraphttps://img.qb5200.com/download-x/dist/js/bootstrap.min.js 

可以看出这里去加载js脚本时寻找的是src/目录下的node_modules目录, 所以加载失败。这意味着angular-cli.json文件中配置的路径时相对于网站根目录的路径, 接着做如下更改:

 "app": [
 {
  ...
  "styles": [
   "../node_modules/bootstraphttps://img.qb5200.com/download-x/dist/css/bootstrap.min.css"
  ],
  "scripts": [
   "../node_modules/bootstraphttps://img.qb5200.com/download-x/dist/css/bootstrap.min.css",
   "../node_modules/bootstraphttps://img.qb5200.com/download-x/dist/css/bootstrap.min.css"
  ],
  ...
 }
] 

再次运行网站,成功加载~~~

回看来时路

后来了解到,angular-cli的项目使用webpack来将模块打包, 我们这里配置的scriptsstyles会被打包成scripts.bundle.js styles.bundle.js文件加载到前台页面,而后就可以正常使用这些第三方库了~~~

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们