# 使用 webpack 打包时,如何更好地利用 long term cache

Issue

欢迎在 Issue 中交流与讨论: Issue 81 (opens new window)

查阅了很多前辈的资料,总结大致如下:(最后附上链接) long term cache即“持久性缓存” Use [chunkhash] to add a content-dependent cache-buster to each file. Use compiler stats to get the file names when requiring resources in HTML. Generate the chunk-manifest JSON and inline it into the HTML page before loading resources. Ensure that the entry point chunk containing the bootstrapping code doesn’t change its hash over time for the same set of dependencies.

1.使用 [chunkhash] 为每个文件增加一个内容相关的缓存清道夫; Separate development and production configs and use [name].js for development and [name].[chunkhash].js in production.

2.使用编译统计在 HTML 中获取资源时取得文件名;html-webpack-plugin (opens new window)

3.生成 JSON 格式的模块清单文件,并在 HTML 页面加载资源之前内联进去; To fix that, we should use chunk-manifest-webpack-plugin (opens new window) which will extract that manifest to a separate JSON file.

4.保证包含启动代码的入口块不会对于同样的依赖生成不同的哈希值;(3.x 以前的版本是使用 CommonsChunkPlugin 来做代码分离的——将公共库(vendor)和应用程序代码分离开来,并创建一个显式的vendor chunk以防止它频繁更改。而 webpack 4.x 则是把相关的功能包到了optimization.splitChunks中,直接使用该配置就可以实现代码分离。)

代码示例 (opens new window)版本:"webpack": "^1.10.1" 资料来源: webpack中文文档 (opens new window) Webpack Freestyle 之 Long Term Cache (opens new window) Long-term caching of static assets with Webpack (opens new window) 用 webpack 实现持久化缓存 (opens new window) Webpack 的静态资源持久缓存 (opens new window)

Last Updated: 1/17/2021, 2:02:56 PM