Resolving css background-image url with Webpack

Issue

I am using webpack and simply trying to apply a background-image specified in a url property to an html element.

I’ve looked at several threads (this one for instance) but did not find something that works for me.

Here’s my setup :

// index.js

import React from 'react'
import styles from './styles.css'

const MyComponent = () => {
  return (
    <div className={styles.container}></div>
  )
}

export default MyComponent

// styles.css

.container {
  background-image: url('../../../static/public/images/my-background.jpg');
}

// webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.join(__dirname, "dist"),
    filename: "index.bundle.js"
  },
  mode: process.env.NODE_ENV || 'development',
  resolve: { 
    modules: [path.resolve(__dirname, "src"), "node_modules"],
  },
  devServer: {
    static: path.join(__dirname, 'src')
  },
  plugins: [
    new HtmlWebpackPlugin({
        template: path.join(__dirname, "src", "index.html"),
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'static',
          to: 'static'
        }
      ]
    })
  ],
  module: {
    rules: [
        { 
            test: /\.(js|jsx)$/, 
            exclude: /node_modules/, 
            use: ["babel-loader"] 
        },
        {
            test: /\.(css)$/,
            use: ["style-loader", "css-loader"],
        },
        {
          test: /\.(jpg|png|svg|gif)$/,
          use: ['url-loader', 'file-loader'],
        },
    ],
},
}

When reaching localhost I do see the path being resolved :
enter image description here

However, when I try to reach that url, all I see is a little white square …

enter image description here

This is definitely not the image. I do find the image present in my build in ./dist/static/public/images/my-background.jpg

Note that the image has a large size : 3842 × 2162

I think this has to do with webpack loader configuration, but did not quite find how to adjust it to get it to work here. Any help would be very appreciated !

Solution

You are may be using a new version of Webpack, where url-loader and file-loader are deprecated and Asset Modules are the alternatives.

Try using:

{
      test: /\.(jpg|png|svg|gif)$/,
      type: 'asset/resource',
},

instead.

For more information click here.

Answered By – SomoKRoceS

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published