检测网页更新并通知用户刷新,支持webpack、vite
什么时候检测更新
- 首次加载
- 轮询(default: 10 * 60 * 1000 ms)
- script及哦啊本资源加载失败 (404 ?)
- 标签页refocus or revisible
安装
# vite
pnpm add @plugin-web-update-notification/vite -D
# webpack plugin
pnpm add @plugin-web-update-notification/webpack -D
配置
关键:禁用index.html文件的缓存
通过nginx禁用缓存
# nginx.conf
location / {
index index.html index.htm;
if ( $uri = '/index.html' ) { # disabled index.html cache
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
try_files $uri $uri/ /index.html;
}
通过html meta标签禁用缓存
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
</head>
</html>
webpack配置
// vue.config.js(vue-cli project)
const { WebUpdateNotificationPlugin } = require('@plugin-web-update-notification/webpack')
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// ...other config
configureWebpack: {
plugins: [
new WebUpdateNotificationPlugin({
logVersion: true,
}),
],
},
})
vite配置
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { webUpdateNotice } from '@plugin-web-update-notification/vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
webUpdateNotice({
logVersion: true,
}),
]
})
注意:希望用户点击页面就检测更新需要配置一个手动检测更新
// vue-router check update before each route change
router.beforeEach((to, from, next) => {
window.pluginWebUpdateNotice_.checkUpdate()
next()
})
vue3+vite 项目下本地运行时window上没有挂载pluginWebUpdateNotice_(为什么我也不知道,有知道的可以告诉我?),所以调用之前需要加个判断
// vue-router check update before each route change
router.beforeEach((to, from, next) => {
window.pluginWebUpdateNotice_ && window.pluginWebUpdateNotice_.checkUpdate()
next()
})