typescript 如何使用 Webpack 和 Angular2 包含外部 css 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34908641/
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-10-21 03:14:05  来源:igfitidea点击:

How to include an external css file using Webpack and Angular2?

typescriptangularwebpack

提问by born2net

I am trying to add an external reference to a CSS file in Angular2 using Webpack. My css is defined as

我正在尝试使用 Webpack 在 Angular2 中添加对 CSS 文件的外部引用。我的 css 被定义为

{ test: /\.css$/, loader: "style-loader!css-loader" },

in my webpack.config.js file and I can load css just fine when doing in a head of a typescript file:

在我的 webpack.config.js 文件中,当在打字稿文件的头部执行时,我可以很好地加载 css:

require("./styles/style.css");

However when I try and load a CSS file inline inside a component as in:

但是,当我尝试在组件内内联加载 CSS 文件时,如下所示:

@Component({
selector: 'todo-list',
template: `
            <section class="todoapp">                 
            </section>
`,
styles: [require('./Todolist.css')], // <--------------
directives: [TodoItem],
providers: [TodosService]
...

I get an error of: EXCEPTION: TypeError: s.replace is not a function

我收到以下错误:EXCEPTION: TypeError: s.replace is not a function

I also tried to load CSS via:

我还尝试通过以下方式加载 CSS:

styles: [require('style-loader!css-loader!./Todolist.css')]

but not much luck

但运气不佳

any help is appreciated

任何帮助表示赞赏

regards

问候

Sean

肖恩

回答by born2net

What did the trick was to load css as raw text in the webpack.config.js

诀窍是将 css 作为原始文本加载到 webpack.config.js 中

{
    test: /\.css$/,
    loader: 'raw!postcss'
},

regards

问候

回答by squadwuschel

My current Solution for WebPack 2 with Angular 2 for css or scss Loader;

我当前使用 Angular 2 for css 或 scss Loader 的 WebPack 2 解决方案;

  {
      test: /\.css$/,
      loader: [
          ExtractTextPlugin.extract({ fallbackLoader: "style-loader", loader: 'css-loader' }),
          'to-string-loader',
          'css-loader'
      ],
      exclude: [helpers.root('Content')],
      include: [helpers.root('App')]
  },
  {
      test: /\.scss$/,
      loader: [ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: ['css-loader'] }),
          'to-string-loader',
          'css-loader',
          'sass-loader'
      ],
      exclude: [helpers.root('Content')],
      include: [helpers.root('App')]
  },

Plugins:

插件:

  new ExtractTextPlugin({ filename: "[name].css" }),

And now you can use the following in your component

现在您可以在组件中使用以下内容

@Component({
   selector: 'logmonitor',
   styleUrls: ['./logmonitor.component.scss', './logmonitor.component.css'],
   templateUrl: './logmonitor.component.html'
})

my current DevDependencies are:

我目前的 DevDependencies 是:

 "devDependencies": {
   "@types/node": "6.0.51",
   "angular2-template-loader": "0.6.0",
   "awesome-typescript-loader": "2.2.4",
   "css-loader": "0.26.1",
   "css-to-string-loader": "0.1.2",
   "file-loader": "0.9.0",
   "url-loader": "0.5.7",
   "html-loader": "0.4.4",
   "svg-url-loader": "1.1.0",
   "less": "2.7.1",
   "less-loader": "2.2.3",
   "node-sass": "3.13.0",
   "sass-loader": "4.0.2",
   "style-loader": "0.13.1",
   "raw-loader": "0.5.1",
   "to-string-loader": "1.1.5",
   "clean-webpack-plugin": "0.1.4",
   "extract-text-webpack-plugin": "2.0.0-beta.4",
   "html-webpack-plugin": "2.21.0",
   "webpack-notifier": "1.4.1",
   "webpack": "2.1.0-beta.27",
   "webpack-dev-middleware": "1.8.4",
   "webpack-dev-server": "2.1.0-beta.12",
   "webpack-md5-hash": "0.0.5",
   "webpack-merge": "0.17.0",
   "typescript": "2.0.10",
   "typings": "2.0.0"
 }

Updatefor Webpack 2.2.1 and extract-text-webpack-plugin 2.0.0-rc.3 here the solution above is not working any more.

更新Webpack 2.2.1 和 extract-text-webpack-plugin 2.0.0-rc.3 此处上述解决方案不再有效。

addional devdependencies

额外的依赖

"extract-text-webpack-plugin": "2.0.0-rc.3",
"postcss-loader": "1.3.0",
"postcss-import":  "9.1.0",
"autoprefixer": "6.7.2",
"webpack": "2.2.1",

you need to add a postcss.config.js in your root of your app with the content

你需要在你的应用程序的根目录中添加一个 postcss.config.js 的内容

module.exports = {
    plugins: [
         require('postcss-import')(),
         require('autoprefixer')()
    ]
};

and the new rule for scss is the following

scss 的新规则如下

{
    test: /\.scss$/,
    loader: [
        { loader: 'raw-loader' },
        { loader: 'sass-loader', query: { sourceMaps: true } },
        { loader: 'postcss-loader' }
    ],
    exclude: [helpers.root('Content')],
    include: [helpers.root('App')]
 }

回答by Downhillski

I have posted an answer for the similar question, I hope it will help with you to understand how the styles/styleUrlsworks in angular2. There is a piece of code I proved to append css to the application through your component.

我已经发布了类似问题的答案,希望它能帮助您了解styles/styleUrlsangular2 中的工作原理。我证明有一段代码可以通过您的组件将 css 附加到应用程序中。

Load external css style into Angular 2 Component

将外部 css 样式加载到 Angular 2 组件中

回答by Ramast

Modules you would need to install:

您需要安装的模块:

css-loaderstyle-loaderand optional but recommendedurl-loader

css-loaderstyle-loader可选但推荐url-loader

Changes to your webpack config (development)module: { loaders: [ // CSS { test: /\.css$/, loader: "style-loader!css-loader", }, /* rest of your loaders */ ]

更改您的 webpack 配置(开发module: { loaders: [ // CSS { test: /\.css$/, loader: "style-loader!css-loader", }, /* rest of your loaders */ ]

In your main javascript file include your css file

在您的主要 javascript 文件中包含您的 css 文件

import '../css/bootstrap.min.css';

import '../css/bootstrap.min.css';

Now in case of bootstrap in particular you will get errors like this:

现在,特别是在引导程序的情况下,您将收到如下错误:

ERROR in ./~/css-loader!./client/css/bootstrap.min.css Module not found: Error: Cannot resolve module 'url-loader' @ ./~/css-loader!./client/css/bootstrap.min.css 6:3278-3330 6:3348-3400

ERROR in ./~/css-loader!./client/css/bootstrap.min.css Module not found: Error: Cannot resolve module 'url-loader' @ ./~/css-loader!./client/css/bootstrap.min.css 6:3449-3503

ERROR in ./~/css-loader!./client/css/bootstrap.min.css Module not found: Error: Cannot resolve module 'url-loader' @ ./~/css-loader!./client/css/bootstrap.min.css 6:3533-3586

./~/css-loader!./client/css/bootstrap.min.css 中的错误未找到模块:错误:无法解析模块“url-loader”@ ./~/css-loader!./client/css/ bootstrap.min.css 6:3278-3330 6:3348-3400

./~/css-loader!./client/css/bootstrap.min.css 中的错误未找到模块:错误:无法解析模块“url-loader”@ ./~/css-loader!./client/css/ bootstrap.min.css 6:3449-3503

./~/css-loader!./client/css/bootstrap.min.css 中的错误未找到模块:错误:无法解析模块“url-loader”@ ./~/css-loader!./client/css/ bootstrap.min.css 6:3533-3586

In that case u will need to download the mentioned files locally and add this entry to your webpack config (inside "loaders"section like the first one above)

在这种情况下,您需要在本地下载提到的文件并将此条目添加到您的 webpack 配置中(在"loaders"上面的第一个部分中)

{
    test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
    loader: 'url-loader',
    options: {
      limit: 10000
    }
}]

This is why u need to install url-loader package but it's only required if your css rely on other image/font files.

这就是为什么你需要安装 url-loader 包,但只有当你的 css 依赖于其他图像/字体文件时才需要它。

Note:Apparently for production use it's better to use a more complicated setup that involve ExtractTextPluginmentioned by @squadwuschel

注意:显然对于生产用途,最好使用ExtractTextPlugin@squadwuschel 提到的更复杂的设置

Here is all the details you might need https://webpack.github.io/docs/stylesheets.html

这是您可能需要的所有详细信息 https://webpack.github.io/docs/stylesheets.html