食指 发表于 7 天前

Vue项目发布后浏览器缓存问题解决方案

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/.${version}.css`,
            chunkFilename: `assert/css/.${version}.css`,
      }
    },
    configureWebpack: {
      output: isProduction ?{ // 输出 添加时间戳到打包编译后的js文件名称
            filename: `assert/js/js.${version}.js`,
            chunkFilename: `assert/js/js.${version}.js`,
      } : {},
   }
}
2.3 配置nginx

但是 index.html 在服务器端可能是有缓存的,需要在服务器配置不让缓存 index.html。之前我们有写过文章Jenkins自动化发布Vue项目,我们同样在default.conf中配置。我们禁止对html页面缓存,对js等缓存,这样在首页始终可以获取最新的html页面,进入后自然可以使用最新的js打包文件,从而解决缓存问题
    location / {
      root   /usr/share/nginx/html;
      indexindex.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发布浏览器缓存问题内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/javascript/3267979jl.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Vue项目发布后浏览器缓存问题解决方案