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();
})
相关推荐
志存高远6613 分钟前
Kotlin 的 suspend 关键字
前端
www_pp_25 分钟前
# 构建词汇表:自然语言处理中的关键步骤
前端·javascript·自然语言处理·easyui
YuShiYue44 分钟前
pnpm monoreop 打包时 node_modules 内部包 typescript 不能推导出类型报错
javascript·vue.js·typescript·pnpm
天天扭码1 小时前
总所周知,JavaScript中有很多函数定义方式,如何“因地制宜”?(ˉ﹃ˉ)
前端·javascript·面试
一个专注写代码的程序媛1 小时前
为什么vue的key值,不用index?
前端·javascript·vue.js
vvilkim1 小时前
React 与 Vue:两大前端框架的深度对比
vue.js·react.js·前端框架
장숙혜1 小时前
ElementUi的Dropdown下拉菜单的详细介绍及使用
前端·javascript·vue.js
火柴盒zhang1 小时前
websheet之 编辑器
开发语言·前端·javascript·编辑器·spreadsheet·websheet
某公司摸鱼前端1 小时前
uniapp 仿企微左边公司切换页
前端·uni-app·企业微信
WKK_1 小时前
uniapp自定义封装tabbar
前端·javascript·小程序·uni-app