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

前端 未结 4 985
慢半拍i
慢半拍i 2021-01-18 01:29

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

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


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 02:01

    Modules you would need to install:

    css-loader style-loader and optional but recommended url-loader

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

    In your main javascript file include your css file

    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

    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)

    {
        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.

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

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

提交回复
热议问题