vite前端版本升级,刷新页面

创建versionUpdatePlugin文件

javascript 复制代码
// versionUpdatePlugin.js

const writeVersion = async (versionFile, content) => {
    const fs = await import('fs').then((module) => module.default);
    // 写入文件
    fs.writeFile(versionFile, content, (err) => {
        if (err) throw err
    })
}

export default (options) => {
    let config
    return {
        name: 'version-update',

        configResolved(resolvedConfig) {
            // 存储最终解析的配置
            config = resolvedConfig
        },

        async buildStart() {
            const fs = await import('fs').then((module) => module.default);
            const path = await import('path').then((module) => module.default)
            // 生成版本信息文件路径
            const file = config.publicDir + path.sep + 'version.json'
            // 这里使用编译时间作为版本信息
            const content = JSON.stringify({ version: options.version })
            if (fs.existsSync(config.publicDir)) {
                writeVersion(file, content)
            } else {
                fs.mkdir(config.publicDir, (err) => {
                    if (err) throw err
                    writeVersion(file, content)
                })
            }
        },
    }
}

修改vite.config.js文件

css 复制代码
1. const now = new Date().getTime(); // 定义一个时间戳

2.   plugins: [
    versionUpdatePlugin({
      version: now
    })
  ],
  plugins中引入versionUpdatePlugin方法
3. 定义全局变量
  define: {
    __APP_VERSION__: now,
  }

使用

javascript 复制代码
// 添加 beforeEach 导航守卫
router.beforeEach(async (to, from, next) => {
    await versionCheck() // 版本监控
    next()
});

// 版本监控
const versionCheck = async () => {
    if (process.env.NODE_ENV === 'development') return
    const response = await axios.get('version.json')
    if (__APP_VERSION__ !== response.data.version) {
        // console.log('有新版本,刷新页面');
        setTimeout(() => {
            window.location.reload()
        }, 500)
    }
}
相关推荐
一tiao咸鱼11 小时前
前端转 agent # 03 - Pydantic v2 数据校验深入
前端·后端
Cobyte11 小时前
23.Vue Vapor 组件 attrs 的实现
前端·javascript·vue.js
前端H12 小时前
生成式 UI 实战:AI 如何重塑前端界面
前端·人工智能·ui
懂懂tty12 小时前
Web前端性能指标
前端
绝世唐门三哥13 小时前
vue3中页面返回时刷新首页的处理方案
开发语言·前端·javascript
东方小月13 小时前
agent-skills:把资深工程师的‘工作流’,装进你的AI编程里
前端·架构·代码规范
Maynor99613 小时前
AI Coding 零基础实战教程|第五部分:完整项目案例实操
java·前端·人工智能·claude code·ai coding
binbin_5213 小时前
React 井字棋教程:用一个小游戏理解组件和状态
前端·react.js·前端框架
梦曦i14 小时前
uni-router新推useUniEventChannel,彻底解决页面通信难题
前端·uni-app
柯克七七14 小时前
给老项目加了 TypeScript,本来只想自己爽,结果全公司代码审查标准被我抬高了
前端·vue.js·typescript