我想将内容哈希添加到我的webpack配置中生成的图像中。这些文件是通过散列输出的,但我不确定如何将这些文件插入到我的html中。用pug和HtmlWebpackPlugin生成的Html。
Webpack.config.js的相关部分:
{
test: /\.(jpeg|jpg|png|gif)$/,
use: [
'file-loader?name=images/[name].[contenthash:4].[ext]',
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65
}
}
}
]
},
new HtmlWebpackPlugin({
template: './src/pug/index.pug',
filename: 'index.htm',
inject: true
})pug格式的图像,其中我想要正确的文件名输出:
img(src='/images/logo.png') <-- this needs to be img(src='/images/logo.64fd.png')发布于 2021-02-19 03:24:48
我也有同样的问题;下面是我开发的解决方案中的代码示例。
对我有帮助的主要是pug-loader README.md "Embedded resources"部分:“试着对所有嵌入的资源使用require,用webpack来处理它们。”
只要您正确需要您的文件,Webpack会将它们添加到依赖图中,并根据您为每种文件扩展名类型定义的配置规则进行处理。此处理包括根据在文件加载器options.name配置对象中指定的方法,将contenthash添加到HTML输出中的图像文件名中。
Webpack配置:
// webpack.common.js
// (edited/trimmed for clarity)
module.exports = {
module: {
rules: [{
test: /\.(jpeg|jpg|png|gif)$/,
use: [
{
loader: "file-loader",
/**
* use `name` to specify how and where images should be outputted
*
* 1. use the image's filepath to set the URL path from which it's served
* 2. use the image's filename and contenthash to set its URL filename
*/
options: {
name: "[path][name].[contenthash].[ext]",
// you may need to set `outputPath` too if you want
// to specify how/where images should be outputted
},
},
{
loader: 'image-webpack-loader'
},
],
}],
},
plugins: [
new HtmlWebpackPlugin({
// set the base path that will be prepended on all relative-path tag attributes
// ex: <img src/>, <link href/>, <script src/>, etc.
publicPath: "/",
}),
],
}Pug模板:
// page.pug
// (edited/trimmed for clarity)
img(
alt="Accessible alternate text"
src=require("./images/image.jpg").default
)我还在下面列出了我的依赖项版本;由于包版本的不同,可能会有配置上的差异,但应该应用相同的一般原则。祝好运!
// package.json
// (edited/trimmed for clarity)
"devDependencies": {
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.1.0",
"image-webpack-loader": "^7.0.1",
"pug": "^3.0.0",
"pug-loader": "^2.4.0",
"webpack": "^5.22.0",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2",
"webpack-merge": "^5.7.3"
}https://stackoverflow.com/questions/63396719
复制相似问题