Vite+Vue3实现版本更新检查,实现页面自动刷新
Vite+Vue3实现版本更新检查,实现页面自动刷新
- 1、使用Vite插件打包自动生成版本信息
- 2、Vite.config.ts配置
- 3、配置环境变量
- 4、路由配置
现有一个需求就是实现管理系统的版本发版,网页实现自动刷新页面获取最新版本
搜索了一下,轮询的方案有点浪费资源,不太适合我的
现在使用了路由跳转的方式去实现 这里有个大佬
就是在每次打包的时候生成一个version.json版本信息文件,在页面跳转的时候请求服务端的version.json的版本号和浏览器本地的版本号对比,进行监控版本的迭代更新,并对页面进行更新
1、使用Vite插件打包自动生成版本信息
Vite插件即是Vite虚拟模块, Vite 沿用 Rollup 的虚拟模块官网有解释(第一次了解到Vite虚拟模块)
这里的文件位置为 /src/utils/versionUpdatePlugin.ts
//简易Ts版
// versionUpdatePlugin.js
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配置
define全局变量配置,不懂可以看看这个
import versionUpdatePlugin from './src/utils/versionUpdatePlugin'; //Rollup 的虚拟模块// 打包时获取版本信息
const CurrentTimeVersion = new Date().getTime();
const viteConfig = defineConfig((config) => {const now = new Date().getTime()return {...define: {// 定义全局变量'process.env.VITE__APP_VERSION__': CurrentTimeVersion,},plugins: [...versionUpdatePlugin({version: CurrentTimeVersion,}),],...}})
3、配置环境变量
环境变量分开了,没有直接放在 .env中
//development 和 production
# 版本
VITE__APP_VERSION__ = ''
4、路由配置
路由跳转是自动检测版本,有新版本则自动更新页面
// 版本监控
const versionCheck = async () => {
//import.meta.env.MODE 获取的是开发还是生产版本的if (import.meta.env.MODE === 'development') return;const response = await axios.get('version.json');// eslint-disable-next-line no-undef//process.env.VITE__APP_VERSION__ 获取环境变量设置的值,判断是否与生成的版本信息一致if (process.env.VITE__APP_VERSION__ !== response.data.version) {// eslint-disable-next-line no-undefElMessage({message: '发现新内容,自动更新中...',type: 'success',showClose: true,duration: 1500,onClose: () => {window.location.reload();},});}
};
// 这里在路由全局前置守卫中检查版本
router.beforeEach(async () => {await versionCheck()
})
继续多学习…