Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack 5: Image src in html when using contentHash

I am able to get the src attribute correct when importing images in my js files. But not when specifying img src url in my html code. How to get the correct url in html automatically whenver i build the project.

webpack.config

module.exports = {
  entry: {
    "main-page": "./src/scripts/index.js",
  },
  output: {
    filename: "bundle.[name].[contenthash].js",
    path: path.resolve(__dirname, "./dist"), 
    publicPath: "static/", 
  },
  module: {
    rules: [
      {
        test: /\.(png|jpg)$/,
        use: ["file-loader"],
      },
      {
        test: /\.hbs$/,
        use: ["handlebars-loader"],
      },
    ]
  },
  plugins: [
      new HTMLWebpackPlugin({
      template: "src/handlebars/index.hbs",
      filename: "index.html",
    }),
  ],
}
somefile.js

import Image from "../assests/img.jpg";

const imgEle=document.createElement("img");
imgEle.src=Image; // gets corrrectly refrenced to md5hash.jpg in the bundle
index.hbs (using handlebars)

<img src="?" /> // what to do here so that it correctly gets refrenced.
like image 319
Rajat Aggarwal Avatar asked May 03 '26 22:05

Rajat Aggarwal


1 Answers

In order to make it work you have to configure the option inlineRequires of the hbs loader which is addressed here.

Here's what you have to refine for both file-loader and handlebars-loader. Please check the inline comments for both loaders:

// webpack.config.js

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.(png|jpg)$/,
        use: [{
          loader: 'file-loader',
          // Turn off esModule setting 👇
          options: {
            esModule: false,
          }
        }],
      },
      {
        test: /\.hbs$/,
        use: {
          loader: "handlebars-loader",
          options: {
            // This option tells to to require the assest 👇
            inlineRequires: '\/assests\/',
          }
        },
      },
    ],
  },
}

Finally, you simply specify the path to image in your templat.

// index.hbs
// specify the path to asset which must relate to this file (`index.hbs`)
<img src="../assests/img.jpg" />
like image 142
tmhao2005 Avatar answered May 06 '26 11:05

tmhao2005



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!