如何将 css 库添加到使用 angular-cli@webpack 生成的项目

How to add css library to project generated with angular-cli@webpack

创建新项目并将其升级到 webpack 版本后,我想添加 bootstrap 的 CSS。

我尝试了文档 [1] 中描述的方法,但它似乎不起作用。

我无法使用cdn版本,因为我的用户可能需要在没有访问外部网络的情况下工作。

[1] https://github.com/angular/angular-cli#global-library-installation

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

.

$ ng --version
angular-cli: 1.0.0-beta.11-webpack.2
node: 5.4.1
os: linux x64

或者我只是不明白应该发生什么? 在 dist 目录中的 ng build 之后没有 CSS 文件并且没有添加任何内容到 index.html

我认为您必须在 node_modules 前面添加 ../,因为 node_modules 文件夹在目录树中是上一级。 像这样: "../node_modules/bootstrap/dist/css/bootstrap.css"

如果您升级到 1.0.0-beta.11-webpack.3 或更高版本,您可以使用 angular-cli.jsonapps[0].styles 属性 列出要导入的外部样式表。有了这个,您不必向 index.html.

添加任何内容

1.0.0-beta.11-webpack.2升级到1.0.0-beta.11-webpack.3,运行:

npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@1.0.0-beta.11-webpack.3

注意:如果您在 运行ning ng version 上遇到 SyntaxError: Unexpected token ... 错误,您可能需要升级到 Node.js 6。有关详细信息,请参阅 https://github.com/angular/angular-cli/issues/1883

如果您生成一个新项目并安装 Bootstrap,您的 angular-cli.json 应该如下所示:

{
  "project": {
    "version": "1.0.0-beta.11-webpack.3",
    "name": "demo"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": "assets",
      "index": "index.html",
      "main": "main.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "app",
      "mobile": false,
      "styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css"
      ],
      "scripts": [],
      "environments": {
        "source": "environments/environment.ts",
        "prod": "environments/environment.prod.ts",
        "dev": "environments/environment.dev.ts"
      }
    }
  ],
  "addons": [],
  "packages": [],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "prefixInterfaces": false,
    "lazyRoutePrefix": "+"
  }
}

ng build 期间 angular-cli.jsonapps[0].styles 属性 中的所有 css 文件都编译成 styles.bundle.js 并且此文件包含在index.html。如果您查看此文件,您可以在其中找到所有样式。所以它按预期工作。