Webpack不从CSS background-image属性加载图像

时间:2016-02-26 20:33:21

标签: webpack vue.js

我不知道该怎么做......我正在使用带有CSS,样式,sass和stylus加载器的Webpack。这是我的webpack配置...当我使用类似的东西时,图像不显示:

body
    background-image: url('bg.jpg')

如果我在带有<img>标记的HTML中包含图片,则它们可以正常工作......

我的webpack配置:

var path = require('path')

module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: path.resolve(__dirname, '../dist/static'),
    publicPath: '/static/',
    filename: '[name].js'
  },
  resolve: {
    extensions: ['', '.js', '.vue'],
    alias: {
      'src': path.resolve(__dirname, '../src')
    }
  },
  resolveLoader: {
    root: path.join(__dirname, 'node_modules')
  },
  module: {
    preLoaders: [
      {
        test: /\.vue$/,
        loader: 'eslint',
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        loader: 'eslint',
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css?sourceMap', 'sass?sourceMap']
      },
      {
        test: /\.woff/,
        loader: 'url?prefix=font/&limit=10000&mimetype=application/font-woff'
      }, {
        test: /\.ttf/,
        loader: 'file?prefix=font/'
      },
      {
        test: /\.eot/,
        loader: 'file?prefix=font/'
      },
      {
        test: /\.svg/,
        loader: 'file?prefix=font/'
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'url?limit=10000&name=[name].[ext]?[hash:7]',
          'image-webpack?{progressive:true, optimizationLevel: 7, interlaced: false, pngquant:{quality: "65-90", speed: 4}}'
        ]
      }
    ]
  },
  eslint: {
    formatter: require('eslint-friendly-formatter')
  },
  vue: {
    loaders: {
      sass: 'style!css!sass?indentedSyntax'
    }
  }
}

1 个答案:

答案 0 :(得分:8)

您需要prepend the image url ~。这告诉Sass加载器使用webpack的require解析来解析文件路径;默认情况下,它将像普通的Sass图像url()一样被解析。所以它应该是background-image: url('~bg.jpg') - 然后确保webpack知道(通过你的配置)如何找到bg.jpg所在的目录。