如何解决使用由webpack生成的[contenthash]插入图像
我想在我的webpack配置中生成的图像中添加内容哈希。这些文件输出时带有哈希值,但是我不确定如何将它们插入到HTML中。带有Html的是通过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 "Embedded resources" 部分:“尝试对所有嵌入式资源使用 require,并使用 webpack 处理它们。”
只要您正确地需要您的文件,Webpack 就会将它们添加到其依赖关系图中,并根据您为每种文件扩展名类型定义的配置规则来处理它们。此处理包括根据您在文件加载器 contenthash
配置对象中指定的方法,将 options.name
添加到 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: "/",}),}
帕格模板:
// 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"
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。