Positioning error

The project was compiled using Webpack4, and the background image specified using the URL method in the packaged style will not display properly

.bgurl{
  background-image: url('/images/abc.jpeg')}Copy the code

The above styles failed to compile in Webpack and are configured as follows

// stylus
[
  loader: MiniCssExtractPlugin.loader,
  {
    loader: 'css-loader'.options: {
      importLoaders: 2,}},'postcss-loader'.'stylus-loader'
]
Copy the code

MiniCssExtractPlugin configuration item publicPath according to the solution found on the Internet, but still error. It seems that the problem is not the MiniCssExtractPlugin. After careful investigation. Locating the error is actually a csS-Loader compilation error.

Go to NPM to find the CSS-Loader configuration and find the following

Name Type Default Description
url {Boolean|Function} true Enables/Disables url/image-set functions handling

url

Type: Boolean|Function Default: true

Enables/Disables url/image-set functions handling. Control url() resolving. Absolute URLs are not resolving.

Examples resolutions:

url(image.png) => require('./image.png')
url('image.png') = >require('./image.png')
url(./image.png) => require('./image.png')
url('./image.png') = >require('./image.png')
url('http://dontwritehorriblecode.com/2112.png') = >require('http://dontwritehorriblecode.com/2112.png')
image-set(url('image2x.png') 1x, url('image1x.png') 2x) => require('./image1x.png') and require('./image2x.png')
Copy the code

The default url attribute is true. This attribute forces the interpretation of the image using the URL in the style, and addresses the image address (the same as the CSS address) by default. Because the image with the same address does not exist (the actual image exists in another directory), the compilation error occurs.

Fix webPack configuration

[{loader: MiniCssExtractPlugin.loader,
    options: {
      publicPath: '//localhost:3000/',}}, {loader: 'css-loader'.options: {
      importLoaders: 2.url: false}},'postcss-loader'.'stylus-loader'
]
Copy the code

PublicPath this configuration can share webpack. The output configuration, but advice in MiniCssExtractPlugin. Independent setting in the loader. There are two reasons

  1. CSS url (…). The images are generally relative path addressing images
  2. O&m will provide static resource server, images have exclusive domain name address

Url Sets the configuration URL of csS-loader to false so that CSS-Loader does not parse urls in styles (…) Image address, keep the original properties

So far, webpack style URL () background image problem solved, I hope to help you

The open source project