与webpack 3的CSS中的图像

时间:2018-01-05 17:35:20

标签: css reactjs webpack sass

关于这个问题,我已经查看了每个堆栈溢出帖子,但仍然无法解决此问题。我无法获得background-image:url()为我的生活工作。当我说我经历过每一篇文章时,我都不是在开玩笑。为什么webpack在这个简单的任务中如此令人沮丧?下面是我的webpack.config中的模块。请有人帮助我这两天。

 module: {
        loaders: [
            {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel-loader']},
            {test: /bootstrap\/js\//, loader: 'imports?jQuery=jquery' },
            {test: /\.css$/, loader: 'style-loader!css-loader'},
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract('css!scss')
            },
            {test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
            {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
            {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
            {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=images/svg+xml" },
            {test: /\.(jpe?g|png|gif|svg)$/i, loaders: [
                'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
                'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false',
                'url-loader?limit=90000000&name=src/images/[name].[ext]'
            ]}

        ]
    }

1 个答案:

答案 0 :(得分:0)

您需要使用resolve-url-loader才能在scss中使用相对路径,以下是如何使用它的示例:

module: {
  rules: [{
    test: /\.scss$/,
    exclude: /node_modules/,
    use: ExtractTextPlugin.extract({
      use: [
        {
          loader: 'css-loader',
          options: {
            modules: true,
            importLoaders: 1,
            localIdentName: '[local]'
          }
        }, {
          loader: 'resolve-url-loader',
          options: {
            sourceMap: true
          }
        }, {
          loader: 'sass-loader',
          options: {
            outputStyle: 'compressed',
            sourceMap: true
          }
        }
      ]

    })
  }, {
    test: /\.(jpe?g|png|gif|svg)$/,
    loaders: [{
      loader: 'file-loader',
      options: {
        name: '[path][name].[hash:base64:5].[ext]',
        publicPath: '/',
        outputPath: 'img/'
      }
    }, {
      loader: 'image-webpack-loader',
      options: {
        gifsicle: {
          interlaced: false
        },
        optipng: {
          optimizationLevel: 7
        },
        pngquant: {
          quality: '65-90',
          speed: 4
        },
        mozjpeg: {
          progressive: true,
          quality: 70
        }
      }
    }]
  }]
}
  

注意options中的file-loader配置告诉webpack输出图像的位置。

this commit中有一个正在运行的示例。