1

While researching webpack, I came across an example in the official guide "Asset Management" that doesn't work as expected. The same image is used to insert an into the DOM in a js file and as an element background in styles. When using style-loader and css-loader for css, as well as file-loader for images, two output files are generated for one image: normal for the element and empty for the background in css. If we remove all the logic associated with the file-loader from the project, then the image file for the background in css is correct. Why is the official example not working as expected?

project

  |- package.json
  |- webpack.config.js
  |- /dist
    |- bundle.js
    |- index.html
  |- /src
    |- style.css
    |- index.js
    |- icon.png
  |- /node_modules

src/index.js

  import _ from 'lodash';
  import './style.css';
  import Icon from './icon.png';

  function component() {
    const element = document.createElement('div');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    element.classList.add('hello');

    const myIcon = new Image();
    myIcon.src = Icon;+
    element.appendChild(myIcon);

    return element;
  }
  document.body.appendChild(component());

src/style.css

.hello {
  color: red;
  background: url('./icon.png');
}

webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                ],
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: [
                    'file-loader',
                ],
            },
        ],
    },    
};
lichiy
  • 11
  • 3
  • 1
    As a result, I found the answer to the question on my own. The example from the webpack manual was for version 4, where the file-loader is deprecated. In webpack 5 place the file-loader needs to use the built-in asset-loader, with the setting in the configuration: module: { rules: [ { test: /\.png/, type: 'asset/resource' } ] }, – lichiy Dec 31 '21 at 09:16
  • webpack version? – JRichardsz Jul 05 '22 at 17:59

0 Answers0