javascript - 网页包 5 : Image src in html when using contentHash

标签 javascript html webpack

在我的 js 文件中导入图像时,我能够获得正确的 src 属性。 但在我的 html 代码中指定 img src url 时不是。 如何在我构建项目时自动获取 html 中的正确 url。

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.

最佳答案

为了使其正常工作,您必须配置 hbs 加载程序的选项 inlineRequires,地址为 here .

这是您必须为 file-loaderhandlebars-loader 优化的内容。请检查两个加载器的内联注释:

// 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\/',
          }
        },
      },
    ],
  },
}

最后,您只需在模板中指定图像的路径。

// index.hbs
// specify the path to asset which must relate to this file (`index.hbs`)
<img src="../assests/img.jpg" />

关于javascript - 网页包 5 : Image src in html when using contentHash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67457247/

相关文章:

javascript - jquery性能问题, Action 注册

javascript - 如何使用 javascript 根据单元格的值更改单元格的背景颜色?

javascript - 找不到主模块中的 WEBPACK5 错误 : Error: Can't resolve './src'

javascript - 尝试访问 javascript 对象值时出现 "SyntaxError: Unexpected token, expected , "

javascript - 使用复选框在数组中添加和删除对象

javascript - 在业务催化剂结帐中选择 PayPal 时如何隐藏信用卡字段

javascript - 检查某物是否可迭代

html - 如何在 import.io 连接提取中包含 CSS

android - 使用 TalkBack 或 VoiceOver 时样式居中的复选框不可选中

Angular mat-select 和 webpack module federation 事件问题