如何配置webpack来加载导入css文件的css?

时间:2016-05-13 21:27:10

标签: webpack

我使用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(...)阶段的加载?我无法从node_modules ...

重写css文件

2 个答案:

答案 0 :(得分:2)

解决: 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'
  }
]

答案 1 :(得分:0)

我在webpacking onsenui的css时遇到了同样的问题...要修复它,我必须告诉webpack通过文件加载器加载字体,如Serge van den Oever answered,但是以提供的新方式在回答时webpack doc

此外,我不得不删除' style-loader'从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