在 Vue 前端项目中,每次打包发布后,用户可能会因为浏览器缓存而继续使用旧版本,导致代码不匹配、页面功能异常或缺失。为了解决这个问题,我们需要一种机制,能够在用户访问应用时自动检测新版本,并在版本不一致时强制刷新浏览器,以获取最新资源。
1. 版本号文件管理
在 public/appVersion.json 中存储版本号,每次打包时自动更新。
{
"version": "1.0.0"
}
2. 版本号更新脚本
在 src/updateVersion.js 文件中,实现每次打包时自动更新 appVersion.json。
文件路径:src/updateVersion.js
const fs = require("fs");
const path = "./public/appVersion.json";
const jsonFile = JSON.parse(fs.readFileSync(path, "utf8"));
console.log("jsonFile", jsonFile);
const oldVersion = jsonFile.version;
const newVersion = new Date().getTime();
console.log("newVersion", newVersion);
const newJsonFile = { version: newVersion };
try {
fs.writeFileSync(path, JSON.stringify(newJsonFile), "utf8");
console.log("版本号已经更新为", newVersion);
} catch (err) {
// 处理错误
console.error("版本号更新失败", err);
}
上面两个文件创建完成后,运行 node ./src/updateVersion.js 测试版本号是否更新,结果如图
3. 版本号检测与刷新逻辑
在 App.vue 中,检测版本号变化,并在版本不一致时刷新页面。
文件路径:src/App.vue
import axios from 'axios';
watch:{
$route(){
const oldVersion = localStorage.getItem('appVersion')
axios.get('/appVersion.json').then(res=>{
const newVersion = res.data.version
console.log('获取到版本号',oldVersion,newVersion)
if(parseInt(newVersion) !== parseInt(oldVersion)){ // localStorage存储的类型是string,数据类型转换一下防止判断错误
console.log('版本升级了,强制刷新')
// 更新版本号并刷新页面
localStorage.setItem('appVersion',newVersion)
window.location.reload(true);
}
})
},
},
4. 修改打包命令
在 package.json 的 scripts 中,修改 build 命令,使其在打包前先更新 appVersion.json。
文件路径:package.json
{
"scripts": {
"build": "node ./src/updateVersion.js && vue-cli-service build"
}
}
每次打包后,将获取的版本号与本地存储的进行对比,不一致则刷新页面。