Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack not loading images from CSS background-image property

Tags:

webpack

vue.js

I have no clue what to do... I am using Webpack with CSS, style, sass and stylus loaders. Here is my webpack config... Images do not show up when I use something like:

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

If I include image inside HTML with <img> tag they work normally...

My webpack config:

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'
    }
  }
}
like image 617
Primoz Rome Avatar asked Dec 16 '25 14:12

Primoz Rome


1 Answers

You need to prepend the image url with a ~. This tells the Sass loader to use webpack's require resolution to resolve the file path; by default it will be resolved like a normal Sass image url(). So it should be background-image: url('~bg.jpg') -- and then just make sure webpack knows (via your config) how to find the directory that bg.jpg is in.

like image 73
Brendan Gannon Avatar answered Dec 19 '25 05:12

Brendan Gannon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!