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();
})
相关推荐
程序员阿峰几秒前
WebSocket 原理解析
前端
Lee川3 分钟前
JavaScript 继承进化史:从原型链的迷雾到完美的寄生组合
前端·javascript·面试
米饭同学i3 分钟前
微信小程序实现故事线指引动画效果
前端
阿懂在掘金6 分钟前
为什么写 Vue 强烈建议用 Setup?除了复用,更是代码组织
前端·vue.js
sorryhc16 分钟前
我让 AI 帮我写了一个 Code Agent!
前端·openai·ai编程
工边页字17 分钟前
面试官:请详细介绍下AI中的token,越详细越好!
前端·人工智能·后端
anyup17 分钟前
月销 8000+,uView Pro 让 uni-app 跨端开发提速 10 倍
前端·uni-app·开源
前端Hardy1 小时前
别再忽略 Promise 拒绝了!你的 Node.js 服务正在“静默自杀”
前端·javascript·面试
前端Hardy1 小时前
别再被setTimeout闭包坑了!90% 的人都写错过这个经典循环
前端·javascript·vue.js
小林coding1 小时前
专为程序员打造的简历模版来啦!覆盖前端、后端、测开、大模型等专业简历
前端·后端