const { writeFile, mkdir, existsSync } = require('fs')
// 动态生成版本号
const createVersion = () => {// mkdir('./dist', { recursive: true }, (err) => {//检测dist目录是否存在if (existsSync('./dist')) {writeFile(`./dist/version.json`, `{"version":"${Date.now()}"}`, (err) => {if (err) {console.log('写入version.json失败')console.log(err)} else {console.log('写入version.json成功')}})} else {setTimeout(createVersion, 1000)}// })
}
setTimeout(createVersion, 10000)
以下两种方式都需要在vue.config.js里加上上面这段代码
第一种
// auto-update.js
/** @Description: 自动更新*/import Vue from 'vue'
import Modal from './updateModal.vue'let currentVersion // 当前版本
let hidden = false // 页面是否隐藏
let setTimeoutId// 获取版本号
const getVersion = async () => {return fetch(process.env.VUE_APP_BASE_URL + 'version.json?timestep=' + Date.now()).then(res => res.json())
}// 检查更新
const checkUpdate = async () => {const version = (await getVersion()).versionif (Number(version) > Number(currentVersion)) {const result = confirm('发现新版本,点击确定更新')if (result) {location.reload() // 刷新当前页}}
}// 自动更新
const autoUpdate = async () => {setTimeoutId = setTimeout(async () => {console.log(setTimeoutId, '这是个检查自动更新的定时器')// 页面隐藏了就不检查更新if (!hidden) {checkUpdate()}autoUpdate()}, 10 * 1000)
}// 停止检测更新
const stop = () => {if (setTimeoutId) {clearTimeout(setTimeoutId)setTimeoutId = ''}
}// 开始检查更新
const start = async () => {currentVersion = (await getVersion()).versionautoUpdate()// 监听页面是否隐藏document.addEventListener('visibilitychange', () => {console.log(document.hidden, '能监听到啥')hidden = document.hiddenif (hidden) {stop()} else {checkUpdate()autoUpdate()}})
}export default { start }
第二种
// update.worker.js, 我放在了public下let currentVersion // 当前版本
let hidden = false // 页面是否隐藏
let setIntervalId// 获取版本号
const getVersion = async () => {// return fetch('http://localhost:8080/version.json?timestep=' + Date.now()).then(res => res.json())// const url = window.location.origin // 无法读取windowreturn fetch('https://xxxx.com/version.json?timestep=' + Date.now()).then(res => res.json(), { cache: 'no-store' })
}// 检查更新
const checkUpdate = async () => {let isUpdate = falseconst version = (await getVersion()).versionif (Number(version) > Number(currentVersion)) {console.log('发现新版本,点击确定更新--update.worker.js')return (isUpdate = true)} else {return (isUpdate = false)}
}// 停止检测更新
const stop = () => {if (setIntervalId) {clearInterval(setIntervalId)setIntervalId = ''}
}self.onmessage = async event => {var data = event.datacurrentVersion = (await getVersion()).versionif (data.pageVisibility) {stop()return}setIntervalId = setInterval(async () => {const isUpdate = await checkUpdate()if (isUpdate) {stop()self.postMessage({isUpdate: true})}}, 5 * 1000)console.log(data, '子线程worker.js')
}
随便一个全局文件里使用下面代码
var worker = new Worker('http://localhost:8080/update.worker.js')const url = window.location.originvar worker = new Worker(url + 'update.worker.js')// var worker = new Worker('/update.worker.js')let data = { pageVisibility: false }worker.postMessage(data)worker.onmessage = function(event) {console.log(event.data, 'worker主线程1')if (event.data?.isUpdate) {// const result = confirm('发现新版本,点击确定更新')// if (result) {// // location.reload(true) // 刷新当前页// // window.location.reload(true)// window.location.replace(window.location.href)// }Notification({title: '页面更新提示',message: '网页内容有更新,请按shift+F5刷新页面',duration: 0,type: 'success',onClose: () => {}})worker.terminate()}}worker.onerror = function(event) {console.log(event)// console.error(event.filename + ':' + event.message)//如果发生错误,立即终止代码worker.terminate()}// 监听页面是否隐藏document.addEventListener('visibilitychange', () => {console.log(document.hidden, '能监听到啥-html')let hidden = document.hiddendata.pageVisibility = hidden})