首页 > 解决方案 > 使用 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')

标签: webpackwebpack-file-loaderpug-loader

解决方案


我有同样的问题;下面是我开发的解决方案的代码示例。

对我有帮助的主要是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"
}

推荐阅读