Vue<前端页面版本检测>

发布时间:2026/7/2 5:07:24
Vue<前端页面版本检测> 写在开头点赞 收藏 学会为什么需要版本检测1. 解决浏览器缓存问题静态资源缓存浏览器会缓存 JS、CSS 等静态资源用户可能继续使用旧版本用户体验影响用户无法及时获取新功能导致功能缺失或操作异常2. 保障功能一致性功能同步确保所有用户都能使用最新的功能和修复数据一致性避免因版本差异导致的数据不一致问题3. 提升用户体验主动提醒在新版本发布后主动通知用户更新无缝升级减少用户手动刷新页面的需求版本检测核心思路整体架构构建阶段 → 版本文件生成 → 运行时检测 → 版本对比 → 用户提醒技术实现要点1. 版本标识生成构建时生成每次打包时生成唯一的版本标识时间戳方案使用时间戳确保每次构建版本号唯一2. 版本文件部署JSON 格式将版本信息保存为version.json文件静态访问通过 HTTP 请求可直接访问版本文件3. 客户端检测机制定时轮询定期检查服务器版本文件版本对比比较本地缓存版本与服务器版本智能提醒仅在版本不一致时提醒用户版本检测实现步骤步骤一构建版本文件生成脚本创建build-version.js文件123456789101112131415161718// build-version.js 自动生成版本文件脚本constfs require(fs)constpath require(path)// 方案A使用时间戳作为版本标识最简单确保每次打包唯一constversion newDate().getTime().toString()// 版本文件内容constversionJson {version: version,updateTime:newDate().toLocaleString()// 可选添加更新时间便于排查}// 写入version.json文件项目根目录constversionPath path.resolve(__dirname,public,version.json)fs.writeFileSync(versionPath, JSON.stringify(versionJson,null, 2),utf-8)console.log(✅ 自动生成版本文件成功版本号${version})步骤二修改构建命令在package.json中修改构建命令12345{scripts: {build:prod:node build-version.js vue-cli-service build}}步骤三配置 Vue 构建过程在vue.config.js中添加版本文件复制配置12345678910111213141516chainWebpack(config) {// ... 其他配置// 复制 version.json 到 dist 目录config.plugin(copy).tap(args {consthasVersionJson args[0].some(item item.fromversion.json)if(!hasVersionJson) {args[0].push({from: path.resolve(__dirname,public/version.json),to: path.resolve(__dirname,dist/version.json)})}returnargs})}步骤四实现版本检测工具类创建src/utils/versionUpdate.js123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128// src/utils/versionUpdate.jsimport { Notification }fromelement-ui/*** 版本更新检测工具类仅生产环境启用轮询内置环境判断*/classVersionUpdate {constructor(options {}) {this.config {versionFileUrl:/version.json,// 版本文件地址localVersionKey:cmpVersion,// 本地存储的版本号keydisableFetchCache:true,// 禁用Fetch缓存pollInterval: 5 * 60 * 1000,// 5分钟轮询一次hasNotified:false// 是否已提醒过用户有新版本}Object.assign(this.config, options)// 定时轮询定时器this.pollTimer null// 识别当前环境Vue CLI 4 自动注入的环境变量this.isProduction process.env.NODE_ENV production}/*** 核心方法执行版本检测*/async checkVersion(isInit false) {try{if(this.config.hasNotified)returnfalseconstlocalVersion localStorage.getItem(this.config.localVersionKey) ||constfetchOptions {}if(this.config.disableFetchCache) {fetchOptions.cache no-cache}constresponse await fetch(this.config.versionFileUrl, fetchOptions)if(!response.ok) {thrownewError(版本文件请求失败状态码${response.status})}constlatestVersionInfo await response.json()constserverVersion latestVersionInfo.versionif(isInit) {this.cacheLatestVersion(serverVersion)returntrue}if(serverVersion serverVersion ! localVersion) {this.config.hasNotified trueconsole.log(有新版本可用, latestVersionInfo)Notification({title: 有新版本可用,dangerouslyUseHTMLString:true,message: p stylefont-size:12px;建议点击刷新页面以获取最新功能和修复/p p stylecolor:#cccccc;font-size:12px;更新时间${latestVersionInfo.updateTime}/p,duration: 0,customClass:check-version-notify,onClick: () {this.forceRefreshPage()},onClose: () {this.resetNotifyFlag()}})returntrue}else{// 版本一致时重置提醒标记便于后续轮询检测新版本this.config.hasNotified false// console.log(当前已是最新版本已缓存最新版本号)returnfalse}}catch(error) {console.warn(版本检测异常不影响应用运行, error.message)returnfalse}}/*** 启动定时轮询检测内置环境判断仅生产环境生效*/async startPolling() {// 核心非生产环境直接返回不启动轮询if(!this.isProduction) {console.log(当前为非生产环境不启动版本检测轮询)return}// 生产环境正常启动轮询this.stopPolling()// 先停止已有轮询避免重复启动this.checkVersion(true)// 立即执行一次检测this.pollTimer setInterval(() {this.checkVersion()},this.config.pollInterval)console.log(生产环境版本轮询检测已启动每隔${this.config.pollInterval / 1000 / 60}分钟检测一次)}/*** 停止定时轮询检测*/stopPolling() {if(this.pollTimer) {clearInterval(this.pollTimer)this.pollTimer nullconsole.log(版本轮询检测已停止)}}/*** 重置提醒标记*/resetNotifyFlag() {this.config.hasNotified false}// 缓存最新版本号cacheLatestVersion(version) {localStorage.setItem(this.config.localVersionKey, version)this.resetNotifyFlag()}// 强制刷新页面forceRefreshPage() {window.location.reload(true)}}constversionUpdateInstance newVersionUpdate()export { VersionUpdate, versionUpdateInstance }exportdefaultversionUpdateInstance创建自定义.check-version-notify的版本检测全局样式123456789101112131415161718192021// 版本检测通知样式.check-version-notify{border: 3px solid transparent !important;cursor: pointer;background-color: rgba(255, 255, 255, 0.6) !important;backdrop-filter: blur(5px);:hover{border: 3px solid $--color-primary !important;}.el-notification__icon{font-size: 18px;height: 18px;}.el-notification__title{font-size: 14px;line-height: 18px;}.el-notification__group{margin-left: 8px;}}步骤五在应用入口启动版本检测在App.vue或合适的入口文件中启动版本检测12345678import versionUpdatefrom/utils/versionUpdate...mounted() {versionUpdate.startPolling()},beforeDestroy() {versionUpdate.stopPolling()}