1、在项目根目录创建resetVersion.js的文件,内容如下
(具体路径可能会有点问题,但是不影响)
const path = require('path');
const fsExtra = require('fs-extra');
const runBuild = async () => {
try {
const OUTPUT_DIR = 'public'; // 输出目录(相对当前文件位置)
const FILENAME = 'version.json'; // 文件名
const versionJson = { // 文件内容
version: 'V' + new Date().getTime(),
};
fsExtra.outputJson(path.resolve(__dirname, `${OUTPUT_DIR}/${FILENAME}`), versionJson, (err) => {
if (err) {
console.error('Failed to write version.json:', err);
} else {
console.log('version.json has been successfully generated.');
}
})
} catch (error) {
process.exit(1);
}
};
runBuild();
2、在package.json的build命令中 && node resetVersion.js
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build && node resetVersion.js",
"lint": "vue-cli-service lint"
},
3、在路由的页面添加路由守卫监听页面是否跟新
import axios from 'axios';
router.afterEach(async (to) => {
const url = '/version.json?v=' + new Date().getTime();
const response = await axios.get(url);
const serverVersion = response.data ? response.data.version : null;
const localVersion = localStorage.getItem('vmp_version');
// 新旧版本号对比
if (serverVersion && serverVersion !== localVersion) {
localStorage.setItem('vmp_version', serverVersion);
// 此处自定义弹窗提示
// window.location.reload();
alert('更新了')
} else {
localStorage.setItem('vmp_version', serverVersion);
}
});
4、具体就打包发布—就此运行成功