Assets in CSS Bundles in Webpack
Now let's make it so that the paths to the .png files are replaced in the CSS files during compilation:
export default {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve('dist')
},
module: {
rules: [
{
test: /\.png$/,
type: 'asset/resource'
},
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'bundle.[contenthash].css'
}),
new HtmlWebpackPlugin(),
],
};
Let's check how it works. Let's connect an image and a style file to the entry point:
import './images/img.png';
import './styles.css';
Let's use the path to the image in the style file:
body {
background: url('images/img.png');
}
After assembling in CSS bundle the path to the image will be changed to the new one:
body {
background: url('the right way from the root');
}
Set the background image in the CSS file.
Connect the image to the entry point.
Perform a build and see which file the image will be copied to and what the new path will look like in the CSS bundle.