How to use images in css with Webpack

user3737841 picture user3737841 · Feb 12, 2016 · Viewed 46.7k times · Source

I am making a React w/ Webpack setup and am struggling to do what seems like should be a simple task. I want webpack to include images, and minimize them like I with gulp but I can't figure it out. I just want to be able to link an image in my css like so:

/* ./src/img/background.jpg */

body { background: url('./img/background.jpg'); }

I have all of my css/js/img folders inside a src folder. Webpack outputs to a dist folder, but I can't figure out how to get images there.

Here is my webpack setup:

 var path = require('path');
 var webpack = require('webpack');
 var HtmlWebpackPlugin = require('html-webpack-plugin');

 module.exports = {
  devtool: 'cheap-eval-source-map',
  entry: [
   'webpack-dev-server/client?http://localhost:8080',
   'webpack/hot/dev-server',
   './src/index.js'
  ],
  output: {
  path: path.join(__dirname, 'dist'),
  //  publicPath: './dist',
  filename: 'bundle.js'
  },
  plugins: [
  new webpack.HotModuleReplacementPlugin(),
  new HtmlWebpackPlugin({
  template: './src/index.html'
   })
  ],
  module: {
  loaders: [{
   exclude: /node_modules/,
   test: /\.js?$/,
   loader: 'babel'
   }, {
  test: /\.scss$/,
  loader: 'style!css!sass'
    }, {
  test: /\.(png|jpg)$/,
  loader: 'file-loader'
  }]
 },

 devServer: {
  historyApiFallback: true,
  contentBase: './dist',
  hot: true
  }
};

Answer

WitVault picture WitVault · Feb 12, 2016

I was stuck with similar issue and found that you can use url-loader to resolve "url()" statements in your CSS as any other require or import statements.

To install it:

npm install url-loader --save-dev

It will install the loader that can convert resolved paths as BASE64 strings.

In your webpack config file use url-loader in loaders

{
  test: /\.(png|jpg)$/,
  loader: 'url-loader'
}

Also make sure that you are specifying your public path correctly and path of images you are trying to load.