Webpack 5:使用contentHash时在html中使用图像src



在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

以下是针对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" />

最新更新