vue3 + vite 实现版本更新检查(检测到版本更新时提醒用户刷新页面)

背景

当一个页面很久没刷新,又突然点到页面。由于一些文件是因为动态加载的,当重编后(如前后端发版后),这些文件会发生变化,就会出现加载不到的情况。进而导致正在使用的用户,点击页面发现加载不顺畅、卡顿问题。

解决思路

使用Vite构建一个插件,在每次打包时自动生成version.json版本信息文件,记录版本信息(最好使用时间戳来作为版本号)。然后在路由跳转时,通过请求服务端的version.json的版本号与浏览器本地的版本号对比来检测是否需要更新,并弹窗提示用户是否立即刷新页面以获取最新版本。

实现代码

1、utils文件下新建versionUpdatePlugin.ts文件

typescript 复制代码
//使用Vite插件打包自动生成版本信息
import fs from "fs";
import path from "path";
 
interface OptionVersion {
	version: number | string;
}
interface configObj extends Object {
	publicDir: string;
}
const writeVersion = (versionFileName: string, content: string | NodeJS.ArrayBufferView) => {
	// 写入文件
	fs.writeFile(versionFileName, content, err => {
		if (err) throw err;
	});
};
export default (options: OptionVersion) => {
	let config: configObj = {
		publicDir: ""
	};
	return {
		name: "version-update",
		configResolved(resolvedConfig: configObj) {
			// 存储最终解析的配置
			config = resolvedConfig;
		},
		buildStart() {
			// 生成版本信息文件路径
			const file = config.publicDir + path.sep + "version.json";
			// 这里使用编译时间作为版本信息
			const content = JSON.stringify({ version: options.version });
			if (fs.existsSync(config.publicDir)) {
				writeVersion(file, content);
			} else {
				fs.mkdir(config.publicDir, err => {
					if (err) throw err;
					writeVersion(file, content);
				});
			}
		}
	};
};

2、Vite.config.ts配置

typescript 复制代码
// 打包时获取版本信息
import versionUpdatePlugin from "./src/utils/versionUpdatePlugin"; 
 
export default (): UserConfig => {
	    const CurrentTimeVersion = new Date().getTime();
 
    	return {
		    define: {
			    // 定义全局变量(转换为时间戳格式)
			    'import.meta.env.VITE_APP_VERSION': JSON.stringify(Date.now()),
		    },
            plugins: [
                // 版本更新插件
			    versionUpdatePlugin({
				    version: CurrentTimeVersion
			    })
            ]
        }
	};
});

3、utils文件下新建versionCheck.ts文件

typescript 复制代码
import { DialogPlugin } from 'tdesign-vue-next';
import axios from 'axios';

// 版本检查
export const versionCheck = async () => {
  const response = await axios.get('version.json');
  console.log('当前版本:', import.meta.env.VITE_APP_VERSION);
  console.log('最新版本:', response.data.version);
  // process.env.VITE__APP_VERSION__  获取环境变量设置的值,判断是否与生成的版本信息一致
  if (import.meta.env.VITE_APP_VERSION !== response.data.version) {
    const confirmDialog = DialogPlugin.confirm({
      header: '版本更新提示',
      body: '检测到新版本,更新之后将能体验到更多好用的功能,是否现在更新?',
      confirmBtn: {
        content: '更新',
        theme: 'primary',
      },
      theme: 'warning',
      onConfirm: () => {
        confirmDialog.update({ confirmBtn: { content: '更新中', loading: true } });
        const timer = setTimeout(() => {
          window.location.reload();
          clearTimeout(timer);
        }, 500);
      },
      onCancel: () => {
        console.log('用户取消了更新');
      },
    });
  }
};

4、路由配置

在路由配置文件(如permission.ts)中调用检查版本函数

typescript 复制代码
import { versionCheck } from "@/utils/versionCheck";
 
router.beforeEach(async (to, from, next) => {
	// 检查版本
	await versionCheck();
})
相关推荐
小二·4 小时前
Pinia 完全指南:用 TypeScript 构建可维护、可测试、可持久化的 Vue 3 状态管理
javascript·vue.js·typescript
bug总结4 小时前
Vue3 实现后台管理系统跳转大屏自动登录功能
前端·javascript·vue.js
用户47949283569154 小时前
同事一个比喻,让我搞懂了Docker和k8s的核心概念
前端·后端
烛阴4 小时前
C# 正则表达式(5):前瞻/后顾(Lookaround)——零宽断言做“条件校验”和“精确提取”
前端·正则表达式·c#
C_心欲无痕4 小时前
浏览器缓存: IndexDB
前端·数据库·缓存·oracle
郑州光合科技余经理4 小时前
技术架构:上门服务APP海外版源码部署
java·大数据·开发语言·前端·架构·uni-app·php
GIS之路5 小时前
GDAL 实现数据属性查询
前端
PBitW6 小时前
2025,菜鸟的「Vibe Coding」时刻
前端·年终总结
mwq301236 小时前
不再混淆:导数 (Derivative) 与微分 (Differential) 的本质对决
前端
小二·6 小时前
Vue 3 组件通信全方案详解:Props/Emit、provide/inject、事件总线替代与组合式函数封装
前端·javascript·vue.js