麻花痒 发表于 2024-9-8 04:20:55

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即可
OK,办理

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Vue项目发布后浏览器缓存问题办理