Vite+Vue3实现版本更新检查,实现页面自动刷新

现有一个需求就是实现管理系统的版本发版,网页实现自动刷新页面获取最新版本
搜索了一下,轮询的方案有点浪费资源,不太适合我的

现在使用了路由跳转的方式去实现 这里有个大佬

就是在每次打包的时候生成一个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-undef
		ElMessage({
			message: '发现新内容,自动更新中...',
			type: 'success',
			showClose: true,
			duration: 1500,
			onClose: () => {
				window.location.reload();
			},
		});
	}
};
// 这里在路由全局前置守卫中检查版本
router.beforeEach(async () => {
  await versionCheck()
})

打包自动修改package.json 的version

还是用到Vite虚拟模块

贴代码

// versionUpdatePlugin.js
import fs from 'fs';
import path from 'path';
function handleType(oldVersion: string, type: string = 'release') {
	var oldVersionArr = oldVersion.split('.');
	//版本号第一位 如:1.2.3 则为 1
	var firstNum = +oldVersionArr[0];
	//版本号第二位 如:1.2.3 则为 2
	var secondNum = +oldVersionArr[1];
	//版本号第三位 如:1.2.3 则为 3
	var thirdNum = +oldVersionArr[2];
	switch (type) {
		case 'release':
			//release分支的处理逻辑
			++secondNum;
			thirdNum = 0;
			break;

		case 'hotfix':
			//hotfix分支的处理逻辑
			++thirdNum;
			break;

		default:
			// 默认按照最小版本处理
			++thirdNum;
			break;
	}
	return firstNum + '.' + secondNum + '.' + thirdNum;
}
export default () => {
	return {
		name: 'version-update',
		buildStart() {
			if (process.env.NODE_ENV === "development") return 
			const url = path.join(process.cwd(), 'package.json');
			const json = fs.readFileSync(url, 'utf-8');
			const pkg = JSON.parse(json);
            // hotfix: 最小版本更新  release:穩定版本 
			const version = handleType(pkg.version, 'hotfix');
            pkg.version = version
			fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2));
		},
	};
};

//vite.config.ts
define: {
		__NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
	},

剩下的就是在APP.vue上做版本的检测,不同则弹出更新提示

// 版本监控
const versionCheck = async () => {
	if (import.meta.env.MODE === 'development') return;
	if (route.path !== '/login') {
		state.getVersion = false;
		// @ts-ignore
		let nextVersion = __NEXT_VERSION__;
		const response = await axios.get(`version.json?${Date.now()}`);
		const localVersion = Local.get('version');
		console.log('R', response.data.version);
		console.log('N', nextVersion);
		console.log('L', localVersion);
		if (response.data.version !== nextVersion && (response.data.version !== localVersion || nextVersion !== localVersion)) {
			state.resVersion = response.data.version;
			state.getVersion = true;
			// Local.set('version', response.data.version);
		}
	}
};
//之前忘记贴代码了
//这是我自己的,暂时没出现问题,仅供参考

继续多学习…

  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
Vue3和Vite实现版本更新自动刷新的方法下: 1. 配置Vite插件:在vite.config.js文件中,可以使用versionUpdatePlugin插件来实现版本更新自动刷新。该插件可以在每次打包生产代码时,在public目录下生成一个version.json版本信息文件,并将版本号定义为全局变量__APP_VERSION__。同时,该插件还可以监控版本迭代更新,并在页面跳转时,通过请求服务器端的version.json文件和浏览器本地缓存的版本号进行对比,从而实现页面自动更新。 ```javascript // vite.config.js import { defineConfig } from 'vite' import versionUpdatePlugin from './versionUpdatePlugin' export default defineConfig((config) => { const now = new Date().getTime() return { define: { __APP_VERSION__: now, // 定义全局变量__APP_VERSION__ }, plugins: [ // 使用versionUpdatePlugin插件 versionUpdatePlugin({ version: now, }), ], // 其他配置项... } }) ``` 2. 创建versionUpdatePlugin插件:在项目根目录下创建一个名为versionUpdatePlugin.js的文件,并在该文件中定义versionUpdatePlugin插件。 ```javascript // versionUpdatePlugin.js export default function versionUpdatePlugin(options) { return { name: 'version-update-plugin', apply: 'build', generateBundle(_, bundle) { const version = options.version const versionInfo = { version: version, } const versionJson = JSON.stringify(versionInfo) // 在public目录下生成version.json文件 this.emitFile({ type: 'asset', fileName: 'version.json', source: versionJson, }) // 其他操作... }, } } ``` 通过以上配置,每次打包生产代码时,会在public目录下生成一个version.json文件,并将版本号定义为全局变量__APP_VERSION__。在页面跳转时,可以通过请求服务器端的version.json文件和浏览器本地缓存的版本号进行对比,从而实现页面自动更新

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值