【问题标题】:How to configure webpack to load css that imports css files?如何配置 webpack 加载导入 css 文件的 css?
【发布时间】:2016-05-13 21:27:09
【问题描述】:

我使用 webpack 从节点模块 onsenui 加载一个 css 文件:

require('onsenui/css/onsenui.css');
require('onsenui/css/onsen-css-components.css');

文件 onsenui/css/onsenui.css 确实导入了相关的 css 文件:

@import url("font_awesome/css/font-awesome.min.css");
@import url("ionicons/css/ionicons.min.css");
@import url("material-design-iconic-font/css/material-design-iconic-font.min.css");

使用 webpack 配置如下:

module: {
 loaders: [
  {
    test: /\.js$/,
    loaders: [ 'babel' ],
    exclude: /node_modules/,
    include: __dirname
  },
  {
    test: /\.css?$/,
    loaders: [ 'style', 'css'],
    include: __dirname
  }
 ]
}

但我的浏览器出现以下错误:

http://localhost:9001/font_awesome/css/font-awesome.min.css Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:9001/material-design-iconic-font/css/material-design-iconic-font.min.css Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:9001/ionicons/css/ionicons.min.css Failed to load resource: the server responded with a status of 404 (Not Found)

css-loader 不处理@import 语句吗?我应该如何解决@import url(...) stagements 的加载问题?我可以从 node_modules 重写 css 文件...

【问题讨论】:

    标签: webpack


    【解决方案1】:

    已解决:css-loader 确实处理 @import url(...) 语句,我忽略了有多个 webpack.config.js 文件...

    我现在在加载字体时遇到了另一个问题,必须添加一个附加规则:

    loaders: [
      {
          test: /\.css?$/,
          loaders: [ 'style', 'css' ],
      },
      {
          test   : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
          loader : 'file-loader'
      }
    ]
    

    【讨论】:

      【解决方案2】:

      我在 webpacking onsenui 的 css 时遇到了同样的问题...为了解决这个问题,我不得不告诉 webpack 通过文件加载器加载字体,如 Serge van den Oever answered,但以 webpack doc 提供的新方式在这个答案的时间。

      此外,我必须从 CSS 加载器列表中删除“样式加载器”,如 explained here

      下面是我最终的 webpack.config.js

      var path = require('path');
      var ExtractTextPlugin = require('extract-text-webpack-plugin');
      
      module.exports = {
        entry: './app/index.js',
        output: {
          filename: 'bundle.js',
          path: path.resolve(__dirname, 'lib')
        },
        module: {
          rules: [{
            test: /\.css$/,
            use: ExtractTextPlugin.extract({
              use: [ /*'style-loader',*/ 'css-loader' ]
            })
          },{
            test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
            use: [ 'file-loader' ]
          }]
        },
        plugins: [
          new ExtractTextPlugin('styles.css'),
        ]
      };
      

      于是,在 lib 目录下创建了 bundle.js、style.css 和很多字体文件。

      HTH

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-15
        • 2017-11-12
        • 2019-01-27
        • 2020-09-25
        • 1970-01-01
        • 2019-09-03
        • 2016-07-26
        • 2019-01-24
        相关资源
        最近更新 更多