'Webpack 5, html images are not grabbed from the specified publicPath folder

in Webpack "webpack.config.js", I set the publicPath of the file-loader to a specific folder "img" the name of the image. after compiling I get the images rendered in the HTML as hash and not showing at all. any hint?

before rendering:

<div><img src="images/nature.jpg" alt="cat" /></div>

after

<div><img src="2cf08b2cc25185b216cf.jpg" alt="cat" /></div>

this is my webpack.config.js

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.js",

  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "./dist"),
    // publicPath: "/dist",
  },
  mode: "none",

  module: {
    rules: [
      
      {
        test: /\.txt$/,
        type: "asset/source",
      },

      { test: /\html$/, use: ["html-loader"] },

      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        // type: "asset/resource",
        use: [
          {
            loader: "file-loader",
            options: {
              name: "[name].[ext]",
              outputPath: "/img/",
              publicPath: "/img/",
            },
          },
        ],
      },
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test: /\.s[ac]ss$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
 
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "styles.css",
      linkType: "text/css",
   
    }),
    new CleanWebpackPlugin(),

    new CleanWebpackPlugin(),
    
    new HtmlWebpackPlugin({
      title: "home",
      template: "./src/index.html",
      filename: "index.html",
   
    }),
  ],
};
[structure][1]
  

this is the structure

enter image description here



Solution 1:[1]

You should add this property esModule: false into html-loader options. Then your img src will be changed you intented.

Without esModule options, html-loader change src path at will.

module: {
  rules: [
    {
      test: /\.html$/i,
      use: [
        {
          loader: 'html-loader',
          options: {
            esModule: false,
          },
        },
      ],
    },
  ], ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lee Hyunsoo