如何将自定义的CSS和JS添加到Angular 4

10
在Angular 2中,我可以像这样将它们添加到 index.html 中:

<link rel="stylesheet" href="css/mycss.css">

但在Angular 4中,它必须添加到 angular-cli.json 文件的样式和脚本数组部分。

在我的情况下,它们似乎根本没有被加载。没有错误,但当我在浏览器中查看应用程序时,我知道样式没有加载。 当我也将样式和js添加到index.html文件中时,它不会被加载,我在控制台中得到404。

我该如何解决这个问题?以下是我的Angular cli版本: @angular/cli:1.0.2 Node:6.9.2


你在将CSS文件添加到“styles”数组后是否重启了服务器?试着让服务器崩溃,然后重新运行“ng serve”。 - Dieterg
你在 angular-cli.json 中配置了什么? - Markus Kollers
你仍然可以将它们作为链接标签放置。Angular-cli会创建一个名为assets的文件夹,将它们放在其中并在index.html文件中引用它们(在src="assets/yourPath.css"下)。 - user4676340
1个回答

14

如果你正在使用angular cli,那么请前往你的.angular-cli.json文件,然后你可以在其中找到"styles":[ ]以及"scripts":[ ],你可以在这些文件中添加你的css和js文件。

 "styles": [
            yourfirst-css-file , //comma (,)is important
            your-second-css-file
          ],

例如:

"styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css"
      ],

"scripts": [
        "../node_modules/jquery/dist/jquery.js",
        "../node_modules/tether/dist/js/tether.js",
        "../node_modules/bootstrap/dist/js/bootstrap.js"
      ],

404错误意味着文件未找到。尝试添加完整的"url"文件夹(src)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接