背景

平时我们在 js 中引用的图片文件会被打包放入打包文件中,但是当在 html 模版中引入 图片时,这个图片不会被打包。如下:
我们先设置模版 html,不做任何操作,直接引用一个图片,如下:

  1. <!-- ./public/index.html -->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <title>Document</title>
  9. </head>
  10. <body>
  11. <div id="app"></div>
  12. <img src="../src/test.jpeg" alt="">
  13. </body>
  14. </html>

然后设置

  1. /** ./webpack.config.js **/
  2. let path = require('path');
  3. let HtmlWebpackPlugin = require('html-webpack-plugin');
  4. //...
  5. let htmlplugins = ['index'].map(chunkName=> {
  6. return new HtmlWebpackPlugin({
  7. filename: `${chunkName}.html`,
  8. inject:'body',
  9. chunks:[chunkName],
  10. template: `./public/${chunkName}.html`
  11. })
  12. })
  13. //...
  14. module.exports = {
  15. //...
  16. module: {
  17. rules: [
  18. {
  19. test: /\.(jpeg|jpg|png|gif)$/,
  20. use: [{
  21. loader: 'url-loader',
  22. options: {
  23. limit: 10240,
  24. outputPath: 'img'
  25. }
  26. }]
  27. }
  28. ]
  29. },
  30. plugins:[
  31. ...htmlplugins
  32. ]
  33. }

直接打包,结果如下:
image.png
image.png
通过结果我们就可以发现这是有问题的,图片没有被打包,路径也没有被改变。

解决方法

安装 html-withimg-loader

yarn add html-withimg-loader --dev

配置 loader

/** ./webpack.config.js **/
let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');

//...
let htmlplugins = ['index'].map(chunkName=> {
  return new HtmlWebpackPlugin({
    filename: `${chunkName}.html`,
    inject:'body',
    chunks:[chunkName],
    template: `./public/${chunkName}.html`
  })
})
//...
module.exports = {
  //...
  module: {
    rules:[
      {
        test:/\.(htm|html)$/,
        use: 'html-withimg-loader'
      },
      {
        test: /\.(jpeg|jpg|png|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10240,
              esModule: false, // 关闭 esModule
              outputPath: 'img'
            }
          }
        ]
      }
    ]
  }
  plugins:[
    ...htmlplugins
  ]
}

注意:使用 html-withimg-loader 必须把 url-loader 的 esModule 设置为 false,不然路径会被包裹在一个路径中的 default 中。
打包结果如下:
image.png
image.png
这时候我们就发现图片已经被打包了。