webpack - 使用 webpack 生成的 [contenthash] 插入图片
问题描述
我想为我的 webpack 配置中生成的图像添加内容哈希。这些文件是用哈希输出的,但我不确定如何将它们插入到我的 html 中。Html with 是用 pug 和 HtmlWebpackPlugin 生成的。
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
})
哈巴狗中的图像,我想要正确的文件名输出:
img(src='/images/logo.png') <-- this needs to be img(src='/images/logo.64fd.png')
解决方案
我有同样的问题;下面是我开发的解决方案的代码示例。
对我有帮助的主要是pug-loader README.md “嵌入式资源”部分:“尝试对所有嵌入式资源使用 require,以使用 webpack 处理它们。”
只要您正确地需要您的文件,Webpack 就会将它们添加到其依赖关系图中,并根据您为每种文件扩展名类型定义的配置规则来处理它们。此处理包括根据您在文件加载器配置对象contenthash
中指定的方法在 HTML 输出中添加您的图像文件名。options.name
网络包配置:
// 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: "/",
}),
],
}
帕格模板:
// 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"
}
推荐阅读
- python-3.7 - 文件“E:\python Project\whatapp_reponse\whatapp\main.py”,第 9 行,在
x = position1[0] TypeError: 'None Type' 对象不可下标 - node.js - 在 MongoDB 中使用带有 Socket.io 的 Change Stream 时,“更改”被多次触发
- .net - 数据库的EFcore日志查询
- python - 格式化 SQL 查询以接受引用值列表
- javascript - 图像幻灯片不适用于以下代码
- vue.js - @vue/cli 4.5.13:热重载不起作用
- python - nidaqmx python在一定时间内计数脉冲
- javascript - “在控制器上未找到公共操作方法‘索引’”错误,即使我从未提及“索引”并提供了控制器的特定路径
- java - 读取 file.txt 并取其中的 int 值,然后将它们放入 2D 数组中用于数独
- c# - 带 DI 的 Newtonsoft 转换器