Perfect solution to the path problem of CSS background image in webpack

Time:2021-2-24

In the style tag of Vue component, there is the following CSS code using background image


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

In webpack, the parsing configuration of CSS loader is as follows


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

After packaging, there is no CSS file found in the dist directory. This is because the CSS file is converted into a JS file.

 

At this time, start the project, the background image is introduced correctly and can be displayed normally.

2. Extract the CSS file to a separate file directory

Use mini CSS extract plugin to extract the CSS file to the CSS directory under the dist directory.

2.1 loader configuration


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

2.2 plugin configuration


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

After packaging, the dist directory structure is as follows

You can see that the image is in the root directory (dist), but the CSS file is in the dist / CSS / directory. Now let’s see how the packaged CSS file refers to the path of the image.

2.3 packaging results


background-image: url(bb65a86a2fe7669e483a56b970bea421.png);

You can see that there is no bb65a86a2fe7669e483a56b970bea421.png image in the dist / CSS directory. Therefore, the picture cannot be displayed normally. The ideal situation is


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

3 solutions

Change the configuration of the loader as follows

{
        loader: MiniCssExtractPlugin.loader,
        options: {
            //The relative path of the file where the current CSS is located relative to the packed root path dist
            publicPath: '../'
        }
    }, 'css-loader', 'less-loader'

summary

The separation of CSS file causes the path error of CSS background image. The core of the solution is to configure the value of publicpath, which is the relative path value of the file directory where the CSS file is located relative to the root directory. For example, the root path is /, and the directory where the CSS file is located is / CSS /, so the relative path is

Unexpected problems

Why is the CSS file mixed into the web pack bundle.js File, but the image was not mixed into bundle.js In the middle???

This article about the perfect solution to the problem of background image path of webpack package CSS is introduced here. For more related content of background image path of webpack package CSS, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!