希望实现:检测是否有新的版本,如果有就自动刷新一下页面。
自动化版本注入 + 自动检测更新并刷新页面
1,scripts/set-version.js,(生成 version.json,可供供前端 fetch 使用)
// scripts/set-version.js
const { writeFileSync } = require('fs');
const { execSync } = require('child_process');
function getGitCommitHash() {
try {
return execSync('git rev-parse --short HEAD').toString().trim();
} catch (e) {
console.warn('⚠️ Git not available, using timestamp as fallback');
return 'unknown';
}
}
function getBuildTimestamp() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hour = String(now.getHours()).padStart(2, '0');
const minute = String(now.getMinutes()).padStart(2, '0');
return `${year}${month}${day}-${hour}${minute}`;
}
const commitHash = getGitCommitHash();
const buildTime = getBuildTimestamp();
const version = commitHash === 'unknown' ? buildTime : `${commitHash}-${buildTime}`;
// 写入 public/version.json(Vite 会原样复制到 dist 根目录)
writeFileSync('./public/version.json', JSON.stringify({ version }, null, 2));
console.log(`✅ Build version generated: ${version}`);
2,vite.config.js(注入全局版本变量)
// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { readFileSync } from 'fs';
// 读取 version.json 获取当前版本(确保与 set-version.js 一致)
let APP_VERSION = 'dev';
try {
const versionFile = JSON.parse(readFileSync('./public/version.json', 'utf-8'));
APP_VERSION = versionFile.version;
} catch (e) {
console.warn('⚠️ version.json not found, using "dev" as version');
}
export default defineConfig({
define: {
'__APP_VERSION__': JSON.stringify(APP_VERSION)
},
plugins: [vue()],
// 其他配置...
});
3. src/main.js(自动检测并刷新)
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
// ==============================
// 🔁 自动版本检测 & 刷新逻辑
// 放在最顶部!确保早于任何组件加载
// ==============================
(function autoUpdateCheck() {
// 防止重复执行(如刷新后再次运行)
if (window.__VERSION_CHECKED__) return;
window.__VERSION_CHECKED__ = true;
// 当前本地版本(由 Vite define 注入)
const currentVersion = __APP_VERSION__;
// 跳过开发环境(localhost / 127.0.0.1)
if (
location.hostname === 'localhost' ||
location.hostname === '127.0.0.1' ||
location.protocol === 'file:'
) {
console.log('[Auto Update] Skipped in development mode');
return;
}
// 请求最新版本(加时间戳防缓存)
fetch('/version.json?t=' + Date.now())
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(data => {
const latestVersion = data.version;
if (latestVersion && latestVersion !== currentVersion) {
console.log(
`%c[Auto Update] New version detected!\nLocal: ${currentVersion}\nRemote: ${latestVersion}`,
'color: #4CAF50; font-weight: bold;'
);
// 强制从服务器重新加载(绕过缓存)
location.reload(true);
} else {
console.log('[Auto Update] Already up to date:', currentVersion);
}
})
.catch(err => {
console.warn('[Auto Update] Check failed, skipping:', err.message);
});
})();
// ==============================
// 结束自动更新检测
// ==============================
// 正常启动 Vue 应用
createApp(App).mount('#app');
4. 修改 package.json 构建命令
{
"scripts": {
"dev": "vite",
"build": "node scripts/set-version.js && vite build",
"preview": "vite preview"
}
}
每次 npm run build 会先生成 version.json,再构建
完成前面4个步骤就可以实现:
部署后效果
- 用户访问
https://your-domain.com/(公众号菜单链接不变) - 页面加载 → 自动请求
/version.json - 若发现新版本 → 静默刷新一次 → 加载最新代码
- 用户无感知,始终使用最新版
**后端可以服务端强制禁用缓存:**在你的 Nginx / 服务器配置中,为以下文件禁用缓存:
# Nginx 示例
location ~* \.(html|json)$ {
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
add_header Expires "0";
}
确保 index.html 和 version.json 永不被缓存。