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:
webpack.config.jsexport 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:
src/index.jsimport './images/img.png';
import './styles.css';
Let's use the path to the image in the style file:
src/styles.cssbody {
background: url('images/img.png');
}
After assembling in CSS bundle the path to the image will be changed to the new one:
dist/bundle.ec64ceadef9be2621b7f.cssbody {
background: url('the right way from the root');
}
Задание 1
Set the background image in the CSS file.
Задание 2
Connect the image to the entry point.
Задание 3
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.