webpack generate css file background-image url picture could not be loaded

Before building the project less when the pretreatment based on the use of specified elements in use webpack3 background-image: url(xxx)time to set the background image, local development is ok, but when the project is compiled output will not find a background image; the current development projects with webpack4 when, also face similar problems; therefore explore the reasons about problems on this opportunity.

Causes problems

webpack3 recurring items in the scene

For css configuration items webpack pseudo code as follows:

output: { // 项目编译输出路径
 path: path.resolve(__dirname, 'dist')
}
// 图片的loader的配置如下:
{ 
  test: /\.(gif|png|jpe?g)(\?\S*)?$/,
  loader: 'url-loader',
  options: {
    limit: 3000,
    name: path.join('static', env === 'development' ? 'img/[name].[ext]' : 'img/[name]_[hash:7].[ext]')
   }
}

// 样式文件打包产出的文件配置如下:
if (env === 'produdtion') {
webpackCfg.plugins.push(
 new ExtractTextPlugin({
   filename: 'static/index_[contenthash:7].css',
   disable: false,
   allChunks: true
 })
)
}

The above configuration in a production environment using css extract-text-webpack-pluginto css style file output, the development environment through style-loaderthe linked document within the html css content; and the picture is larger than the specified limit on the size of the package output file.

At this point in our index.lesssetting body of the background image file as follows:

body {
 background-image: url('./img/bg.png');
}

At this time, local development can see the background picture, and the compiler output css files, background image address can not be loaded properly by testing found to be a problem with the image path, as shown below:

Css content from the point of view of output files, background-image pictures of the body element relative url address is webpack configured output image path, but the actual page to show only to find the path to the picture: /xx/../dist/static/ static / img / bg_ebdbe98.png .

Why is the background image path will be more than a staticprefix? Query data found that:

background-image url relative address set in css file relative to the current directory files obtained css

Because the project is to set output path css dist/static/index_[contenthash:7].css, but the url by url webpack after treatment relative address static/img/bg_[hash:7].png; so the above rule, the picture that is actually loaded address dist/static/static/img/bg_[hash:7].png, will lead to pay more in the picture of a path prefix static directory.

And why local development environment is not a problem because the css style local content development environment output by style-loaderlinking to html document within, which is the path to the background image is relative to the html document directory, it is correct.

webpack4 recurring items in the scene

webpack4 project and project webpack3 different places, webpack4 project using mini-css-extract-pluginplug-ins to handle the css style output, which improves extract-text-webpack-plugina number of problems, one of the more important point is that you can use css thermal loading function. Projects related css drawn configuration is as follows:

plugins: [
  new MiniCssExtractPlugin({
    filename: env === 'production' ? 'static/index.[contenthash:7].css' : 'static/index.css'
  })
],
module: {
 rules: [{
  test: /\.less$/,
  use: [
    {loader: MiniCssExtractPlugin.loader}, 
    {loader: 'css-loader', options: {...} },
    {loader: 'less-loader', options: {...} }
 }]
}

webpack4 projects in development and production environments are using mini-css-extract-pluginplug-ins, so the project will yield css files, both environmental problems will arise;

Solution

After know the cause of the problem, we will know how to solve the problem. The best solution is as follows:

  • webpack3 in extract-text-webpack-pluginthe extract process separate configuration file csspublicPath

If there is not extract-text-webpack-pluginarranged the css publicPath, the values will be used webpack.output.publicPath; css Once the configuration values are relative to the path will publicPath the new setting. But the value of the configuration also need to pay attention. For example, the above file output directory:

dist
│   index.html
└───static
│   │   index.js
│   │   index.css
│   └─img
│       │   bg.png

Picture address is static / img / bg.png , introduced the address index.css picture, the picture of the relative address is relative to the directory of the css file, and finally loaded picture address is static / static / img /bg.png , resulting in an error. At this time, the correct configuration extract-text-webpack-plugin follows:

ExtractTextPlugin.extract({
  fallback: 'style-loader',
  use: loaders,
  publicPath: '../'
});

Thus, the publicPath: '../'配置则是从当前index.css文件的父目录来查找图片。final url path to become "../static/img/bg.png".

  • webpack4 in mini-css-extract-pluginthe loader configurationpublicPath

webpack4 also configure publicPath, but the configuration is slightly different, as follows:

module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: '../',
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
    ],
  },

references

Guess you like

Origin www.cnblogs.com/wonyun/p/11038417.html