How to use images in css with Webpack

CssImageReactjsWebpackLoader

Css Problem Overview


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
  }
};

Css Solutions


Solution 1 - Css

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.

Solution 2 - Css

using background-image: url('./img/background.jpg') in the scss file worked for me, without url-loader. Only had file-loader for .png|.jpg|... etc.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3737841View Question on Stackoverflow
Solution 1 - CssWitVaultView Answer on Stackoverflow
Solution 2 - CssSaloni YadavView Answer on Stackoverflow