前端更新版本通知用户刷新

​ 经常我们更新了前端代码的版本,而用户却不知道。我们的功能明明已经更新了,用户却还在使用老的版本。或者 bug 已经解决了,而用户还是会反馈仍旧出现相同的 bug。我们只好一遍遍的让用户刷新。我们需要一种方法,在前端代码部署了新版本后,项目能够检测到新版本,并提醒用户刷新。

一、记录版本号

​ 通过 webpack/vite 自动生成记录版本的 json 文件。在 vue.config.js 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const { defineConfig } = require('@vue/cli-service')
const fs = require('fs')
const path = require('path')
class VersionPlugin {
apply(compiler) {
compiler.hooks.done.tap('VersionPlugin', () => {
const versionData = { version: new Date().getTime() }
const outputPath = path.resolve(
compiler.options.output.path,
'version.json'
) // 写入打包输出目录
console.log(
'VersionPlugin executed, version:',
versionData.version,
'path:',
outputPath
)
fs.writeFileSync(outputPath, JSON.stringify(versionData))
})
}
}

module.exports = defineConfig({
publicPath: '/app/',
outputDir: 'app',
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
config.plugins.push(new VersionPlugin()) // 在生产环境中添加自定义插件
}
},
})

​ 这样,在生产环境中,当我们执行npm run build命令打包时,就会在指定目录下生成以当前时间戳为版本号的 json 文件

二、版本比较和更新提示

​ 在@/utils/version.js 中,实现检测版本和更新提示的主要逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { ElNotification } from 'element-plus'
import axios from 'axios'
// }
/**
* 检测到版本更新后,notification会一直显示在页面上
*/
function showNotification() {
ElNotification({
showClose: true,
duration: 0,
title: '版本更新提示',
dangerouslyUseHTMLString: true,
message:
"检测到有新版本发布,请<a href='javascript:location.reload()'>刷新</a>页面",
})
}
export async function isNewVersion() {
const url = `//${window.location.host}/app/version.json`
try {
const res = await axios.get(url, {
headers: { 'Cache-Control': 'no-cache' },
})
const newVersion = res.data.version
const localVersion = +window.localStorage.getItem('version')
if (localVersion && localVersion !== newVersion) {
showNotification()
window.localStorage.setItem('version', newVersion)
} else {
window.localStorage.setItem('version', newVersion)
}
} catch (error) {
console.log('获取线上版本号失败utils/version.js', error)
}
}
// 设置定时器每分钟检查一次
setInterval(isNewVersion, 1 * 60 * 1000)

通过请求打包时生成的 version.json 文件,读取其中的版本号,并将其与本地存储的版本号对比以检测版本更新。最后用定时器每隔一段时间检测就好了。到此主要逻辑就完成了

三、在 main.js 中使用

最后在 main.js 中使用上面的功能就可以了

1
import from './utils/version'
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2023-2025 congtianfeng
  • 访问人数: | 浏览次数: