1.vue.config.js 加版本文件自动生成
- 插件机制:
-
- 使用 compiler.hooks.done 钩子(构建完成时触发)
- 通过 tap 方法注册自定义插件
- 版本生成:
-
- 使用当前时间戳作为版本号 new Date().getTime().toString()
- 生成纯数字版本(如 1690789200000)
- 文件输出:
-
- 将版本信息写入 dist/version.json 文件
- 使用 JSON.stringify 格式化输出(缩进2空格)
configureWebpack: config => {
// 版本文件生成插件
config.plugins = config.plugins || []; config.plugins.push({ apply: (compiler) => { compiler.hooks.done.tap('GenerateVersionFilePlugin', (stats) => { const version = new Date().getTime().toString(); fs.writeFileSync( path.resolve(__dirname, './dist/version.json'), JSON.stringify({ version }, null, 2) ); }); } }); }
2.main.js 加版本更新自检功能
基础功能实现:
-
- 定时轮询(5分钟一次)检测版本更新
- 使用 localStorage 存储当前版本
- 检测到更新时弹出提示框
- 防止重复弹窗(isDialogOpen 标志)
- 用户可选择"稍后再说"(stopCheckVersion 标志)
在main.js下添加上述代码 版本更新自检器
import { MessageBox } from 'element-ui'; function checkVersion() { if (isDialogOpen || stopCheckVersion) return; fetch('(/微前端路径)/version.json?t=' + Date.now()) .then(res => { if (!res.ok) throw new Error('version.json not found'); return res.json(); }) .then(data => { const currentVersion = localStorage.getItem('app_version'); if (!currentVersion) { localStorage.setItem('app_version', data.version); } else if (currentVersion !== data.version) { isDialogOpen = true; MessageBox({ title: '版本更新提示', message: '检测到新版本,是否立即刷新页面以获取最新内容?', showCancelButton: true, confirmButtonText: '确定', cancelButtonText: '稍后再说', type: 'warning' }).then(() => { localStorage.setItem('app_version', data.version); window.location.reload(true); }).catch(() => { // 点击稍后再说 本次会话内不再检测 stopCheckVersion = true; }).finally(() => { isDialogOpen = false; }); } }) .catch(err => { console.warn('版本检测失败:', err); }); } checkVersion(); setInterval(checkVersion, 5 * 60 * 1000);