缓存策略

缓存策略

1. 代码分割与缓存优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// webpack.config.js
module.exports = {
output: {
filename: '[name].[contenthash].js', // 使用contenthash而非hash
chunkFilename: '[name].[contenthash].js'
},
optimization: {
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
priority: 10 // 优先级更高
},
commons: {
name: 'commons',
chunks: 'all',
minChunks: 2 // 被至少2个chunk引用
}
}
},
runtimeChunk: 'single' // 将webpack运行时提取到单独文件
}
}

2. 长期缓存策略

  • contenthash:文件内容变化时才改变文件名,而非每次构建都变
  • 分离第三方库:将 node_modules 中的库(如 Antd)提取到单独的 vendors 文件
  • 提取公共模块:多个页面共用的代码提取到 commons 文件

3. 部署与服务器配置

  • 为静态资源设置长期缓存头:
    1
    Cache-Control: max-age=31536000, immutable
  • 使用 Service Workers 进行更精细的缓存控制
  • 考虑使用 CDN 托管公共库

4. 高级优化策略

  • **Webpack 5 模块联邦(Module Federation)**:允许多个独立构建共享依赖
  • externals 配置:不打包特定库,直接从 CDN 引入
    1
    2
    3
    4
    externals: {
    'react': 'React',
    'antd': 'antd'
    }
  • 动态导入:按需加载非关键组件
    1
    const ChartComponent = React.lazy(() => import('./ChartComponent'));

三、效果验证

部署更新后:

  • 仅页面内容变化:只有 main.[contenthash].js 文件名变更
  • 公共库不变:vendors.[contenthash].js 文件名不变,浏览器使用缓存
  • 用户只需下载变化的文件,公共库无需重新下载

通过以上配置,可以实现”页面更新时只需下载变化部分,公共库使用缓存”的效果,大幅提升用户体验和加载性能。


缓存策略
https://zjw93615.github.io/2025/12/06/性能优化/缓存策略/
作者
嘉炜
发布于
2025年12月6日
许可协议