vite 中定义一个全局变量
{
....,
define: {
'__BUILD_TIME__': JSON.stringify(new Date().toLocaleString())
},
}
js 封装一个方法检测打包构建时间
// 检查是否需要提示用户刷新页面
export async function checkForPageRefresh() {
const message = useMessage()
// 获取存储在本地的最新构建时间
const lastBuildTime = localStorage.getItem('lastBuildTime');
// 当前构建时间(通常由构建工具注入,如 webpack 的 DefinePlugin)
const currentBuildTime = __BUILD_TIME__; // 确保你的构建工具注入了这个变量
if (lastBuildTime) {
if (lastBuildTime !== currentBuildTime) {
// 构建时间不同,提示用户刷新
await confirm('新版本已发布,是否立即刷新以获取最新内容?')
localStorage.setItem('lastBuildTime', currentBuildTime);
window.location.reload();
}
} else {
// 首次访问,存储当前构建时间
localStorage.setItem('lastBuildTime', currentBuildTime);
}
}
接下来监听路由切换检查版本更新; 或如果想要更高频率可以使用定时器检测
router.afterEach(() => {
if(import.meta.env.MODE === "production") checkForPageRefresh();
});
image.png