解决 Vue 项目打包上线后客户端缓存的问题

由于重新打包后会导致对应的 js 和 css 文件 hash 值发生变化,客户端不刷新的话就会存在之前的文件找不到,导致报错的问题。

 

通过 build.sh 定义打包命令

复制代码
#!/usr/bin/env bash

# 更新当前时间戳
timestamp=`date '+%s'`
str="{ \"timestamp\": $timestamp }"
echo $str > "public/release.json"

# 根据需要写 打包命令
# rm -rf dist
# rm -rf node_modules
# npm run build
复制代码

 

每次上线前都会创建文件   <项目路径>/public/release.json  例如:

{ "timestamp": 1639550254 }

是一个当前的时间戳。

 

然后设置一个全局的路由守卫

复制代码
import axios from 'axios';
let timestamp;

const testRelease = () => {
    let url = `/release.json?t=${Date.now()}`;
    axios.get(url).then(res => {
        if (res.status === 200) {
            let lastTimestamp = timestamp;  // 上次时间戳
            timestamp = res.data.timestamp; // 当前时间戳
            if (lastTimestamp && lastTimestamp !== timestamp) { // 时间戳不相同的话就重新加载页面
                window.location.reload();
            }
        }
    });
}

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [] // 根据业务定义路由
});

router.beforeEach(async function (to, from, next) {
    testRelease(); // 每次切换路由都调用接口测试时间戳是否更新
    next();
});
复制代码

 

posted @   我不吃饼干呀  阅读(1581)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2017-01-26 学生成绩管理系统3.0(JSP+Servlet+MySQL)
2016-01-26 群赛 ZOJ3741(dp) ZOJ3911(线段树)
点击右上角即可分享
微信分享提示