webpack处理图片

CSS中引用的图片处理

安装 file-loader和url-loader工具

npm install -save-dev file-loader url-loader

配置webpack.config.js

{
  test: /\.(png|jpg|gif)/,
  use: [{
    loader: 'url-loader',
    options: {
      limit: 500000,
      outputPath: './dist/images/',
    }
  }]
}

正常打包后,CSS被解析为JS模块跟随入口文件输出,此时,CSS中所引用的地址是相对于index.html,因此会报错。而使用loader工具后,会分析相应CSS文件的具体引用地址,使其得到正确引用

HTML中引用的图片处理

安装 html-withimg-loader 工具

npm install html-withimg-loader --save

配置loader,同时对于url-loader设置esModule:false(插件工具间的干扰问题)

{
  test: /\.(png|jpg|gif)/,
  use: [{
    loader: 'url-loader',
    options: {
      limit: 500000,
      outputPath: './dist/images/',
      esModule: false,
    }
  }]
},
{
  test: /\.(htm|html)$/i,
  use: ['html-withimg-loader']
},
posted @ 2021-01-14 13:53  Serenpity  阅读(44)  评论(0编辑  收藏  举报