1. 在构建阶段生成 version.json 文件
使用构建工具(如 Webpack/Vite)的插件,在每次打包时生成一个 version.json 文件
// vite.config.js
import { defineConfig } from 'vite';
import fs from 'fs';
export default defineConfig({
plugins: [
{
name: 'generate-version',
buildEnd() {
const versionInfo = {
version: new Date().toISOString(), // 用时间戳作为版本号
};
fs.writeFileSync('./dist/version.json', JSON.stringify(versionInfo));
},
},
],
});
每次打包后,dist/version.json 会包含类似以下内容:
{
"version": "2024-11-26T12:00:00.000Z"
}
2. 在前端检测版本更新
使用 Vite 的 define 配置,将版本号作为全局常量注入到项目中。
import { defineConfig } from 'vite';
export default defineConfig({
define: {
__APP_VERSION__: JSON.stringify(new Date().toISOString()), // 动态注入当前时间作为版本号
},
});
Webpack 中注入当前版本号,在 webpack.config.js 中配置:
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.DefinePlugin({
__APP_VERSION__: JSON.stringify(new Date().toISOString()), // 动态注入版本号
}),
],
};
配置完成后,APP_VERSION 将作为全局变量直接使用:
console.log('当前版本号:', __APP_VERSION__); // 输出当前版本号
const currentVersion = __APP_VERSION__; // 用于版本检测
前端定期请求 version.json 文件,判断是否有新版本。
function checkForUpdate() {
fetch('/version.json', { cache: 'no-store' }) // 禁用缓存获取最新版本
.then(response => response.json())
.then(data => {
if (data.version !== currentVersion) {
showUpdatePrompt(); // 如果版本不一致,提示用户更新
}
})
.catch(error => console.error('版本检测失败:', error));
}
// 显示弹窗提示用户更新
function showUpdatePrompt() {
const modal = document.createElement('div');
modal.innerHTML = `
<div class="update-modal">
<p>发现新版本!是否立即更新?</p>
<button id="update-now">立即更新</button>
<button id="update-later">稍后</button>
</div>
`;
document.body.appendChild(modal);
document.getElementById('update-now').addEventListener('click', () => {
location.reload(true); // 强制刷新加载最新资源
});
document.getElementById('update-later').addEventListener('click', () => {
modal.remove();
});
}
// 定时检查(每隔10分钟)
setInterval(checkForUpdate, 10 * 60 * 1000);