1. 现象描述
每次jenkins自动化发布vue项目后,用户需要手动全部清理历史缓存数据才可以使用系统,用户体验非常不好
2. 解决方案
2.1 配置public/index.html
配置index.html, 在首页启动no-store禁止缓存
<meta http-equiv="pragram" content="no-cache"> <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="expires" content="0">
2.2 配置vue.config.js按时间戳打包
vue 默认配置,打包后 css 和 js 的名字后面都加了哈希值,不会有缓存问题,当然我们也可以自己重新定义根据时间戳
const version = new date().gettime(); module.exports = { css: { // 是否使用css分离插件 extracttextplugin extract: { // 修改打包后css文件名 // css打包文件,添加时间戳 filename: `assert/css/[name].${version}.css`, chunkfilename: `assert/css/[name].${version}.css`, } }, configurewebpack: { output: isproduction ? { // 输出 添加时间戳到打包编译后的js文件名称 filename: `assert/js/js[name].${version}.js`, chunkfilename: `assert/js/js[name].${version}.js`, } : {}, } }
2.3 配置nginx
但是 index.html 在服务器端可能是有缓存的,需要在服务器配置不让缓存 index.html。之前我们有写过文章jenkins自动化发布vue项目,我们同样在default.conf中配置。我们禁止对html页面缓存,对js等缓存,这样在首页始终可以获取最新的html页面,进入后自然可以使用最新的js打包文件,从而解决缓存问题
location / { root /usr/share/nginx/html; index index.html index.htm; if ($request_filename ~* .*\.(js|css|woff|png|jpg|jpeg)$) { expires 100d; } if ($request_filename ~* .*\.(?:htm|html)$) { add_header cache-control "no-store"; } }
如果是通过k8s发布的,可能存在多个nginx,只需配置项目代码中使用的nginx即可
附:清除浏览器 localstorage 缓存
1、更新package.json中的 version 值,每次打包往上递增
2、main.js中,根据 version 判断是否进行缓存清理
const vue_app_version = require('../package.json').version const vers = window.localstorage.getitem('appversion') if(vue_app_version != vers){ localstorage.clear() window.localstorage.setitem('appversion', vue_app_version) location.reload() }
ok,解决
总结
到此这篇关于vue项目发布后浏览器缓存问题解决方案的文章就介绍到这了,更多相关vue发布浏览器缓存问题内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论