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',
],
},
],
},
};