Rajat Aggarwal
Rajat Aggarwal

Reputation: 454

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.

Upvotes: 3

Views: 2279

Answers (1)

tmhao2005
tmhao2005

Reputation: 17524

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" />

Upvotes: 3

Related Questions