1 Do not extract CSS files to a separate file directory

Inside the Style tag of the Vue component is the following CSS code that uses the background image

    background-image: url(".. /assets/img/icon_add.png");
Copy the code

The CSS – Loader parsing configuration in Webpack is as follows

    {
        test: /\.(css|less)$/,
        exclude: path.resolve(__dirname, 'node_modules'),
        use: ['style-loader'.'css-loader'.'less-loader']}Copy the code

There are no CSS files found in the dist directory after packaging. This is because CSS files are converted to JS files.

2 Extract the CSS file to a separate file directory

Use the mini-CSS-extract-Plugin to extract the CSS file separately to the CSS directory in the dist directory.

2.1 loader configuration

    {
        test: /\.(css|less)$/,
        exclude: path.resolve(__dirname, 'node_modules'),
        use: [MiniCssExtractPlugin.loader, 'css-loader'.'less-loader']}Copy the code

2.2 the plugin configuration

        new MiniCssExtractPlugin({
            filename: 'css/[name][contenthash].css',})Copy the code

After packaging, the dist directory structure is as follows

2.3 Packing Result

  background-image: url(bb65a86a2fe7669e483a56b970bea421.png);
Copy the code

Can be seen in the dist/CSS directory no bb65a86a2fe7669e483a56b970bea421. PNG images. So the image doesn’t display properly. The ideal situation would be

background-image: url(.. /bb65a86a2fe7669e483a56b970bea421.png);Copy the code

3 Solution

Change the Loader configuration as follows

{loader: MiniCssExtractPlugin loader, the options: {/ / the current in the CSS file relative to the packaging after the root path of dist publicPath relative path:'.. / '}},'css-loader'.'less-loader'
Copy the code

conclusion

If the CSS file is separated, the path of the CSS background image is incorrect. The core solution is to configure the publicPath value. The publicPath value is the path of the CSS file directory relative to the root directory. For example, the root path is/and the CSS file directory is/CSS /, so the relative path is..

Unexpected problems

Why are CSS files mixed into bundle.js after webpack is packaged, but images not mixed into bundle.js?