react 如何清除前端缓存
清除前端缓存的常用方法
使用版本号或哈希处理静态资源
在构建时通过工具(如Webpack)为文件名添加哈希值,确保每次更新生成新文件名。例如:
output: {
filename: '[name].[contenthash].js',
}
设置HTTP缓存头
在服务器配置中为静态资源添加Cache-Control头,强制浏览器重新验证或禁用缓存:
location /static {
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
强制刷新页面
用户可通过快捷键组合强制跳过缓存加载页面:
- Windows/Linux:
Ctrl + F5 - Mac:
Cmd + Shift + R
使用meta标签禁用缓存
在HTML的<head>中添加以下标签(对部分浏览器有效):
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
清理Service Worker缓存
在注册Service Worker的代码中主动清理旧缓存:
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => caches.delete(cache))
);
});
开发环境禁用缓存
在React开发服务器中配置webpack-dev-server禁用缓存:
devServer: {
hot: true,
inline: true,
disableHostCheck: true,
headers: { 'Cache-Control': 'no-store' }
}






