解决vue项目更新版本后浏览器的缓存问题

  这个问题产品经理很早就提需求了,之前是通过修改webpack的打包的js文件规则解决的。但最近谷歌浏览器更新版本后,这个方法失效了,应该是浏览器默认缓存文件了。最后上网找了这个方法解决的。

方案一:用户手动改浏览器配置

按F12或者右键->检查,勾上disable cache,这个选项是禁用缓存。

方案二:通过代码解决

这个方案第一次更新版本的时候需要清除缓存,但之后更新版本只需要刷新页面就可以获取最新的页面代码了。

1、用webpack打包js文件时,文件名增加一个时间戳,修改 webpack .prod.conf.js 文件

1 const version = new Date().getTime();
2 output: {
3     path: config.build.assetsRoot,
4     filename: utils.assetsPath('js/[name].[chunkhash:8].' + version + '.js'),
5     chunkFilename: utils.assetsPath('js/[name].[chunkhash:8].' + version + '.js')
6 }

2、在 index.html 页面前面加 meta 标签,注意:记得加上,我就是忘记加上了,一直测试不过。

1 <meta http-equiv="pragram" content="no-cache">
2 <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
3 <meta name="viewport" content="width=device-width,initial-scale=1.0"> 

3、html 页面加载脚本的时候给脚本后面加一个时间戳,修改 webpack.prod.conf.js 文件。

 1 new HtmlWebpackPlugin({
 2     filename: config.build.index,
 3     template: 'index.html',
 4     inject: true,
 5     hash: version,
 6     minify: {
 7         removeComments: true,
 8         collapseWhitespace: true,
 9         removeAttributeQuotes: true
10     },CommonsChunkPlugin
11     chunksSortMode: 'dependency'
12 }),

扩展:

vue-cli 里的默认配置,css 和 js 的名字都加了哈希值,所以新版本 css、js 和就旧版本的名字是不同的,不会有缓存问题。但是 index.html 放到服务器里去的时候,index.html 在服务器端可能是有缓存的,这需要在服务器配置不让缓存 index.html。

4、修改 /conf/nginx.conf 配置文件,让index.html不缓存,同时记得重启nginx

1 location = /index.html {
2     add_header Cache-Control "no-cache, no-store";
3 }

参考网页:https://blog.csdn.net/LonewoIf/article/details/89388843

原文地址:https://www.cnblogs.com/daheiylx/p/12705090.html