【问题标题】:How to add hash code in js bundle files for caching如何在 js 捆绑文件中添加哈希码以进行缓存
【发布时间】:2020-02-24 07:45:47
【问题描述】:

我是 webpack 配置的新手,请告诉我如何在生成的 js 包文件中添加哈希码以缓存我的静态资产。提前致谢

【问题讨论】:

    标签: caching webpack bundler


    【解决方案1】:

    要为您生成的包添加哈希码,请将这些行添加到您的 webpack.config.js 文件中。

    output: {
        filename: '[name].[contenthash].js',
        path: path.resolve(__dirname, 'dist'),
    }
    

    用于服务器缓存

    您需要将主块拆分为运行时块和供应商块。为此,您需要在 webpack.config.js 文件的优化部分添加以下代码。

    optimization: {
        runtimeChunk: 'single',
        moduleIds: 'hashed',
        splitChunks: {
            cacheGroups: {
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all',
                },
            },
        },
    }
    

    当您每次更改代码时,其他块/哈希(供应商、运行时)都不会改变。所以客户端(浏览器)不会从缓存中获取它加载的未更改的块。

    参考链接 https://webpack.js.org/guides/caching/

    【讨论】:

    • 感谢您的出色回答。我正在使用 angular 4 和 angular/cli - 1.7.4 版本,不幸的是我在我的项目目录中找不到 webpack.config.js 文件,但是在使用 ng build --prod, chunk 时以某种方式在我的捆绑文件中添加了如下所示的散列{scripts} scripts.ceb96b683ffae2eddfa8.bundle.js (scripts) 884 kB , chunk {0} 0.a8b47f88dc04f7fa6ed1.chunk.js () 576 kB , chunk {1} main.7a51c6f03249686ff85b.bundle.js (main) 2.06 MB,chunk {3} styles.ee63539450fb8a3d65c9.bundle.css (styles) 396 kB,但缓存也没有发生,请帮助我
    • 嗨,我不熟悉 angular。也许这个链接对你修改 webpack 配置文件有用 [stackoverflow.com/questions/39187556/…
    猜你喜欢
    • 2020-07-17
    • 2014-09-25
    • 2016-11-20
    • 2016-09-18
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    相关资源
    最近更新 更多