在我的 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-loader
和 handlebars-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/