Angular Cli 創建的Angular項目應用本地css文件和js文件


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

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

<!doctype html>
<html lang="en">
<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 lang="en"> <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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM