关于webpack:webpack解决样式url背景图问题

6次阅读

共计 1527 个字符,预计需要花费 4 分钟才能阅读完成。

定位谬误

我的项目应用 webpack4 进行编译,打包后的款式中应用 url 办法指定的背景图片不可能失常显示

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

上述款式在 webpack 中编译出错,配置如下

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

始终爆图片未找到的谬误,依照网上找到的解决方案,补全 MiniCssExtractPlugin 配置项 publicPath,但仍然出错。看来问题不是出在MiniCssExtractPlugin。后通过认真排查。定位到谬误其实是css-loader 编译时爆进去的。

去 npm 上找到 css-loader 配置,找到如下内容

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')

属性 url 默认为 true,此属性默认强行解释款式中应用 url 定位的图片,默认寻址该图片地址(与 css 同源地址),因同源地址图片不存在(理论图片存在于另外的目录),造成编译谬误。

修改 webpack 配置

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

publicPath
此项配置能够共用 webpack.output 配置,但倡议在 MiniCssExtractPlugin.loader 中独立设置。有以下两个起因

  1. css 的 url(…)中的图片个别是相对路径寻址图片
  2. 运维会提供动态资源服务器,图片有专属的域名地址

url
css-loader 的配置 url 设为 false,使 css-loader 不解析款式中 url(…)的图片地址,放弃原有属性

至此,webpack 打包款式 url()背景图片问题得以解决,心愿对大家有帮忙

开源我的项目

正文完
 0