" />

欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3+vite實(shí)現(xiàn)版本更新檢查的示例代碼

 更新時(shí)間:2024年11月10日 09:10:38   作者:周三有雨  
本文描述了一個(gè)Vue3和Vite項(xiàng)目中實(shí)現(xiàn)版本更新檢查的解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

背景

當(dāng)一個(gè)頁(yè)面很久沒刷新,又突然點(diǎn)到頁(yè)面。由于一些文件是因?yàn)閯?dòng)態(tài)加載的,當(dāng)重編后(如前后端發(fā)版后),這些文件會(huì)發(fā)生變化,就會(huì)出現(xiàn)加載不到的情況。進(jìn)而導(dǎo)致正在使用的用戶,點(diǎn)擊頁(yè)面發(fā)現(xiàn)加載不順暢、卡頓問題。

解決思路

使用Vite構(gòu)建一個(gè)插件,在每次打包時(shí)自動(dòng)生成version.json版本信息文件,記錄版本信息(最好使用時(shí)間戳來(lái)作為版本號(hào))。然后在路由跳轉(zhuǎn)時(shí),通過請(qǐng)求服務(wù)端的version.json的版本號(hào)與瀏覽器本地的版本號(hào)對(duì)比來(lái)檢測(cè)是否需要更新,并彈窗提示用戶是否立即刷新頁(yè)面以獲取最新版本。

實(shí)現(xiàn)代碼

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

//使用Vite插件打包自動(dòng)生成版本信息
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) {
			// 存儲(chǔ)最終解析的配置
			config = resolvedConfig;
		},
		buildStart() {
			// 生成版本信息文件路徑
			const file = config.publicDir + path.sep + "version.json";
			// 這里使用編譯時(shí)間作為版本信息
			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配置

// 打包時(shí)獲取版本信息
import versionUpdatePlugin from "./src/utils/versionUpdatePlugin"; 
 
export default (): UserConfig => {
	    const CurrentTimeVersion = new Date().getTime();
 
    	return {
		    define: {
			    // 定義全局變量(轉(zhuǎn)換為時(shí)間戳格式)
			    'import.meta.env.VITE_APP_VERSION': JSON.stringify(Date.now()),
		    },
            plugins: [
                // 版本更新插件
			    versionUpdatePlugin({
				    version: CurrentTimeVersion
			    })
            ]
        }
	};
});

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

import { DialogPlugin } from 'tdesign-vue-next';
import axios from 'axios';

// 版本檢查
export const versionCheck = async () => {
  const response = await axios.get('version.json');
  console.log('當(dāng)前版本:', import.meta.env.VITE_APP_VERSION);
  console.log('最新版本:', response.data.version);
  // process.env.VITE__APP_VERSION__  獲取環(huán)境變量設(shè)置的值,判斷是否與生成的版本信息一致
  if (import.meta.env.VITE_APP_VERSION !== response.data.version) {
    const confirmDialog = DialogPlugin.confirm({
      header: '版本更新提示',
      body: '檢測(cè)到新版本,更新之后將能體驗(yàn)到更多好用的功能,是否現(xiàn)在更新?',
      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)中調(diào)用檢查版本函數(shù)

import { versionCheck } from "@/utils/versionCheck";
 
router.beforeEach(async (to, from, next) => {
	// 檢查版本
	await versionCheck();
})

 到此這篇關(guān)于vue3+vite實(shí)現(xiàn)版本更新檢查的示例代碼的文章就介紹到這了,更多相關(guān)vue3 vite版本更新檢查內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論