在WebPack中解析CSS url()

时间:2016-05-17 09:25:53

标签: webpack webpack-dev-server

我在使用WebPack设置url()解析CSS文件时遇到问题。我在Angular项目中有以下目录结构样式。

dist
src
|_ app
   |_ components
      |_ component
         |_component.html
         |_component.css
|_ public
   |_ img

构建时,public的所有内容都会被复制到dist。例如。整个src/public/img文件夹最终在dist/img。所有捆绑文件也内置在dist中。例如。 CSS最终会出现app.hash.css

现在,在HTML文件中我可以img/filename.ext并且它可以正常工作。但是在CSS文件中,我无法正确加载url()

例如,在component.css中,找不到url('img/filename.ext')。如果我url('../../../public/img/filename.ext'),WebPack会找到该文件,但URL未正确构建,最终会有src的整个路径,当然在dist文件夹中找不到。<

这是我的配置的相关部分。我已经为WebPack开发服务器和prod构建设置了它。

var ENV = process.env.npm_lifecycle_event;
var isProd = ENV === 'build';

module.exports = function makeWebPackConfig () {
  var config = {};

  config.entry = {
    app: './src/app/app.js'
  };

  config.output = {
    path: __dirname + '/dist',
    publicPath: isProd ? '/' : 'http://localhost:8080/',
    filename: isProd ? '[name].[hash].js' : '[name].bundle.js',
    chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
  };

  config.module = {
    loaders: [{
      test: /\.html$/,
      loader: 'raw'
    },
    {
      test: /\.css$/,
      loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
    },
    {
      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|otf)$/,
      loader: 'file?name=[path][name].[ext]'
    }]
  }

  config.plugins = [];
  config.plugins.push(
    new HtmlWebpackPlugin({
      template: './src/public/index.html',
      inject: 'body'
    }),
    new ExtractTextPlugin('[name].[hash].css', { disable: !isProd })
  )

  if (isProd) {
    config.plugins.push(
      new CopyWebpackPlugin([{
        from: __dirname + '/src/public'
      }])
    )
  }

  config.devServer = {
    outputPath: path.join(__dirname, 'app'),
    contentBase: './src/public',
    stats: 'minimal'
  };

  return config;
}();

设置中所有路径的哪一部分导致此问题?

E。我应该补充一点,在这种情况下,我无法控制以这种方式从公用文件夹复制文件的事实。

0 个答案:

没有答案
相关问题