背景:由于前端发版用户不及时刷新页面就会造成你看到的页面其实是发版之前的页面,需要每次手动刷新,现在封装2个方法,当有前端代码更新,自动提示用户手动刷新
首先,根目录下创建两个js文件,比如version-update.js这是更新用的,version.js这个是将特定标识写入项目中,以此来区分项目是否更新
version代码如下:
// npm build version
const vueconfig = require('./vue.config.js')
const packageConfig = require('./package.json')
const VERSION_NO = packageConfig.version || ''
const dist_path = `./${vueconfig.outputDir}/homepage.html`
// 获取dist中homepage页面,并在其中写入版本号
const fs = require('fs')
const path = require('path')
const distPath = path.join(__dirname, dist_path)
let htmlContent = fs.readFileSync(distPath, 'utf8')
htmlContent = htmlContent.replace('<head>', `<head><meta name="version_no" content="${VERSION_NO}" >`)
fs.writeFileSync(distPath, htmlContent, 'utf8')
// eslint-disable-next-line no-console
console.log('[ 版本打包成功 ] >', VERSION_NO)
module.exports = VERSION_NO
version-update.js代码如下:
// 版本升级校验
import { MessageBox } from 'element-ui'
// 缓存版本号
let version_no = void 0
// 请求html地址
const fetchUrl = process.env.VUE_APP_PUBLIC_PATH || '/'
const WAIT_TIME = 60 * 1000 // 版本获取间隔时间,每WAIT_TIME请求一次
// message弹窗
let isMessage = false
const setVersionNo = (versionNo) => {
version_no = versionNo
}
const getVersionNo = () => {
return version_no
}
/**
* 清空缓存,重新请求
* @param {string} newVersion
*/
const refreshCache = (newVersion) => {
// 先请求一次页面,设置不缓存,获取最新的html
fetch(`${fetchUrl}?time=${new Date().getTime()}`, { cache: 'no-store' }).finally(() => {
isMessage = false
setVersionNo(newVersion)
// 刷新页面
window.location.reload()
})
}
/**
* 请求页面,获取版本并比对
*/
const fetchNewVersion = () => {
// 在 js 中请求首页地址不会更新页面
fetch(`${fetchUrl}?time=${new Date().getTime()}`, { cache: 'no-store' })
.then((res) => res.text())
.then((text) => {
const oldVersion = getVersionNo()
const el = document.createElement('html')
el.innerHTML = text
const htmlMeta = el.querySelector('meta[name="version_no"]')
if (!htmlMeta) return
const newVersion = htmlMeta.getAttribute('content')
if (newVersion !== oldVersion && !isMessage) {
isMessage = true
MessageBox.alert('发现新版本,请刷新页面后使用', {
type: 'warning',
showClose: false,
confirmButtonText: '立即刷新',
customClass: 'token-massage-alert',
callback: () => {
refreshCache(newVersion)
}
})
}
})
.catch((err) => {
// eslint-disable-next-line no-console
console.log('[ err ] >', err)
})
}
fetchNewVersion()
setInterval(() => {
fetchNewVersion()
}, WAIT_TIME)
/**
* 设置当前版本号
*/
const getCurrentVersionNo = () => {
const htmlMeta = document.querySelector("meta[name='version_no']")
// 获取content的版本号
const versionNo = htmlMeta?.getAttribute('content')
setVersionNo(versionNo)
}
getCurrentVersionNo()
然后在main.js中引用即可
import '../version-update'
最后效果如图: