如何从 webpack angular2 应用程序中的 node_modules 导入 CSS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40071845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 12:12:55  来源:igfitidea点击:

How to import CSS from node_modules in webpack angular2 app

cssangulartypescriptnpmwebpack

提问by Burnee

Let's say that we start with the following starter pack: https://github.com/angularclass/angular2-webpack-starter

假设我们从以下入门包开始:https: //github.com/angularclass/angular2-webpack-starter

After npm installand npm run starteverything works fine.

经过npm installnpm run start一切工作正常。

I want to add an external css module, for example bootstrap 4's css (and only the css). (I know that bootstrap has a bootstrap-loader, but now I'm asking for general solution, so please think about bootstrap 4 here as it could be any other css module that is available via npm).

我想添加一个外部 css 模块,例如 bootstrap 4 的 css(并且只有 css)。(我知道 bootstrap 有一个 bootstrap-loader,但现在我要的是通用的解决方案,所以请考虑这里的 bootstrap 4,因为它可能是通过 npm 可用的任何其他 css 模块)。

I install bootstrap via npm: npm install [email protected] --save

我通过 npm 安装引导程序: npm install [email protected] --save

First I thought that it is enough to add import 'bootstrap/dist/css/bootstrap.css';to the vendor.browser.ts file.

首先我认为添加import 'bootstrap/dist/css/bootstrap.css';到vendor.browser.ts文件就足够了。

But it isn't.

但事实并非如此。

What should I do to have a proper solution?

我该怎么做才能找到合适的解决方案?

Solutions I'm NOT asking for:

我不要求的解决方案:

  1. "Copy the external css module to the assets folder, and use it from there"
    • I'm looking for a solution that works together with npm package.
  2. "Use bootstrap-loader for webpack"
    • As I described above, I'm looking for a general solution, bootstrap is only an example here.
  3. "Use another stack"
    • I'm looking for a solution in the exact starter pack that I've mentioned above.
  1. “将外部 css 模块复制到资产文件夹,并从那里使用它”
    • 我正在寻找与 npm 包一起使用的解决方案。
  2. “为 webpack 使用 bootstrap-loader”
    • 正如我上面所描述的,我正在寻找一个通用的解决方案,bootstrap 只是这里的一个例子。
  3. “使用另一个堆栈”
    • 我正在寻找我上面提到的确切入门包中的解决方案。

回答by Anderson Ivan Witzke

It is possible by using @import '~bootstrap/dist/css/bootstrap.css';on the styles.css file. (Note the ~)

可以通过@import '~bootstrap/dist/css/bootstrap.css';在styles.css 文件上使用。(注意~

Edit: How it works - The '~' is an alias set on the webpack config pointing to the assets folder... simple as that..

编辑:它是如何工作的 - '~' 是 webpack 配置上的一个别名集,指向资产文件夹......就这么简单......

Edit 2: Example on how to configure webpack with the '~' alias... this should go on the webpack config file (usually webpack.config.js)...

编辑 2:关于如何使用 '~' 别名配置 webpack 的示例......这应该放在 webpack 配置文件中(通常webpack.config.js)......

// look for the "resolve" property and add the following...
// you might need to require the asset like '~/bootsrap/...'
resolve: {
  alias: {
    '~': path.resolve('./node_modules')
  }
}

回答by Fabio Antunes

You won't be able to import any css to your vendorsfile using that stack, without making some changes.

如果不进行一些更改,您将无法使用该堆栈将任何 css 导入到您的供应商文件中。

Why? Well because this line:

为什么?好吧,因为这一行:

import 'bootstrap/dist/css/bootstrap.css';

It's only importing your css as string, when in reality what you want is your vendor css in a style tag. If you check config/webpack.commons.jsyou will find this rule:

它只是将您的 css 作为字符串导入,而实际上您想要的是样式标签中的供应商 css。如果你检查config/webpack.commons.js你会发现这个规则:

 {
   test: /\.css$/,
   loaders: ['to-string-loader', 'css-loader']
 },

This rule allows your components to import the css files, basically this:

这个规则允许你的组件导入 css 文件,基本上是这样的:

@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.None,
  styleUrls: [
    './app.component.css' // this why you import css as string
  ],

In the AppComponent there's no encapsulation, because of this line encapsulation: ViewEncapsulation.None,which means any css rules will be applied globally to your app. So you can import the bootstrap styles in your app component:

在 AppComponent 中没有封装,因为这一行encapsulation: ViewEncapsulation.None,意味着任何 css 规则都将全局应用于您的应用程序。因此,您可以在应用程序组件中导入引导程序样式:

@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.None,
  styleUrls: [
    './app.component.css',
    '../../node_modules/bootstrap/dist/css/bootstrap.css'
  ],

But if you insist in importing to your vendor.tsthen you will need to install a new loader, npm i style-loader --save-devthis will allow webpack to inject css to your page. Then you need to create a specific rule, on your webpack.common.js and change the existing one:

但是如果您坚持要导入到您的页面,vendor.ts那么您将需要安装一个新的加载器,npm i style-loader --save-dev这将允许 webpack 将 css 注入您的页面。然后你需要在你的 webpack.common.js 上创建一个特定的规则并改变现有的规则:

 { //this rule will only be used for any vendors
   test: /\.css$/,
   loaders: ['style-loader', 'css-loader'],
   include: [/node_modules/]
 },
 {
   test: /\.css$/,
   loaders: ['to-string-loader', 'css-loader'],
   exclude: [/node_modules/] //add this line so we ignore css coming from node_modules
 },

The firs rule will be only applied when you try to import css, from any package inside node_modulesthe second rule will be applied to any css that you import from outside the node_modules

第一条规则仅在您尝试导入 css 时应用,node_modules第二条规则内的任何包将应用于您从外部导入的任何 cssnode_modules

回答by Himanshu Arora

So here is a way to import various CSSfiles using the angular-cliwhich I find the most convenient.

所以这是一种CSS使用angular-cli我认为最方便的导入各种文件的方法。

Basically, you can refer to the CSSfiles (order is important if you will be overriding them) in the config and angular-cliwill take care of the rest. For instance, you might want to include a couple of styles from node-modules, which can be done as follows:

基本上,您可以参考配置中的CSS文件(如果您将覆盖它们,则顺序很重要)并angular-cli负责其余部分。例如,您可能希望包含来自节点模块的几种样式,可以按如下方式完成:

"styles": [
    "../node_modules/font-awesome/css/font-awesome.min.css",
    "../node_modules/primeng/resources/primeng.min.css",
    "styles.css"
  ]

A sample full-config might look like this:

完整配置示例可能如下所示:

.angular-cli.json

.angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "my-angular-app"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "../node_modules/font-awesome/css/font-awesome.min.css",
        "../node_modules/primeng/resources/primeng.min.css",
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "scss",
    "component": {}
  }
}