Angular Cli 创建的Angular项目应用本地css文件和js文件

在Angular CLI 创建的angular项目中,如何引入css文件呢?

如果直接在index.html中引入,比如下面的代码

<!doctype html>
<html >
<head>
  <meta charset="utf-8">
  <title>CnCommunicator</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" type="text/css" href="../fontello-7275ca86/css/fontello.css">

</head>
<body>
  <app-root></app-root>
</body>
</html>

你将会得到如下错误

Refused to apply style from 'http://localhost:3000/fontello-7275ca86/css/fontello.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

解决方法:

angular 5 之前的版本,在 angular-cli.json 文件中搜索 styles关键字,然后将静态css文件添加到该属性内

            "styles": [
              "src/styles.scss",
              "src/fontello-7275ca86/css/fontello.css",
              "src/icomoon/style.css"
            ]
angular 6+ 的版本, angular-cli.json文件变成了angular.json文件了。因此,要在该文件中添加。

同理,引入assets 或者 js文件方法也类似。 "assets"属性里面设置引入的图片等;"styles"属性里面设置全局引入的 css文件;"scripts"属性里面设置全局引入的js文件

     "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/cn-communicator",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss",
              "src/fontello-7275ca86/css/fontello.css",
              "src/icomoon/style.css"
            ],
            "scripts": []
          },

另外一点,如果你想引入的css/js文件是远程服务器上的,那么直接在index.html里面引用即可。

// index.html
<!doctype html> <html > <head> <meta charset="utf-8"> <title>CnCommunicator</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="stylesheet" type="text/css" href="https://unpkg.com/@fonticonpicker/fonticonpicker/dist/css/base/jquery.fonticonpicker.min.css"> <!-- default grey-theme --> <link rel="stylesheet" type="text/css" href="https://unpkg.com/@fonticonpicker/fonticonpicker/dist/css/themes/grey-theme/jquery.fonticonpicker.grey.min.css"> </head> <body> <app-root></app-root> <script src="../assets/json/left-nav-template-one.sample.js"></script> </body> </html>