webpack解决HTML中img引入图片问题

4,631 阅读1分钟
需求:在index.html中要用img标签引入一张图片。

<img src="./images/logo.png">


本想着用 html-withimg-loader 解决该问题,无果。 

解决方法如下: 

1. 安装依赖

npm i -D  html-webpack-plugin html-loader file-loader

2. 配置webpack.config.js

let HtmlWebpackPlugin = require('html-webpack-plugin')
plugins: [//放着所有的webpack插件    new HtmlWebpackPlugin({      template: './src/index.html',      filename: 'index.html'    }),
]
module: {
  rules: [
    {
      test: /\.(htm|html)$/i,
      use: {
        loader: 'html-loader',
        options: {
          attributes: true
        }
      },
      {
       test: /\.(png|jpg|gif)$/,
        use: {
          loader: 'file-loader',
          options: {
            name: "[name].[ext]", 
            outputPath: "igms",//打包后dist文件夹下将创建的文件目录
            publicPath: "./imgs", //打包后,build目录下,index.html中img src该访问的路径
          }
      }  ]
}

3. 打包后的目录结构


over!