Vue2项目部署后更新版本提示

封装插件VersionPlugin

js 复制代码
const fs = require('fs')
const path = require('path')
const NAME = "cp-version";
class VersionPlugin {
  constructor(options) {
    this.options = {
      versionFileName: 'version.json',
      message: '检测到新版本,点击更新最新版!',
      ...options,
    }
    this.version = process.env[this.options.keyName] || `${Date.now()}.0.0`
  }
  apply(compiler) {
    compiler.hooks.beforeRun.tap(NAME, () => {
      console.log('before run')
      // 生成的版本 json 文件建议放置在 public 文件夹下
      const filePath = path.resolve(
        __dirname,
        '../../public',
        this.options.versionFileName,
      )
      // 生成文件
      this.generateFile(
        filePath,
`{
  "version": "${this.version}",
  "message": "${this.options.message}"
}`,
      )
    })
    compiler.hooks.done.tap(NAME, () => {
      console.log('done ...')
    })
  }
  generateFile(path, content) {
    fs.writeFileSync(path, content)
  }
}

module.exports = VersionPlugin

配置插件

  • vue.config.js
js 复制代码
const VersionPlugin = require('./src/plugins/versionPlugin')

  configureWebpack: (config) => {
    const plugins = []
    plugins.push(new VersionPlugin())
    config.plugins = [...config.plugins, ...plugins]
  })

封装vue插件

js 复制代码
import { MessageBox } from 'element-ui'
export default {
  async install(Vue, options) {
    const CP_VERSION = 'CP_VERSION'
    const checkVersion = async () => {
      let preVersion = localStorage.getItem(CP_VERSION)
      const response = await fetch(`/newcp/version.json?t=${Date.now()}`)
      const data = await response.json()

      console.log('@@之前版本', preVersion)
      console.log('@@当前版本', data.version)
      if (data.version !== preVersion) {
        MessageBox.confirm(data.message, '温馨提示', {
          confirmButtonText: '更新版本',
          showClose: false,
          showCancelButton: false,
          closeOnClickModal: false,
          type: 'warning',
        }).then(() => {
          localStorage.setItem(CP_VERSION, data.version)
          console.log('@@更新版本')
          window.location.reload()
        })
      }
    }
    checkVersion()
    setInterval(() => {
      checkVersion()
    }, 10000)
    Vue.prototype.$checkVersion = checkVersion
  },
}

使用

  • main.js
js 复制代码
import checkVersionNotify from './utils/checkVersionNotify.js'
Vue.use(checkVersionNotify)
相关推荐
IT_陈寒3 分钟前
Vite动态导入差点让我秃头,原来问题出在这
前端·人工智能·后端
白泽_hunter38 分钟前
项目里最常见的 5 个 this 指向坑:从规则到实战彻底讲透
前端
宿67444 分钟前
vue3-pinia
前端·vue.js
白泽_hunter1 小时前
搞懂 JS 数据类型:从 typeof 到手写完整类型判断,一张图理清
前端
日光倾1 小时前
TypeScript 随手记 —— 1
前端·javascript·typescript
自学it的攻城狮2 小时前
elpis-core ,koa实现的系统底座, 沉淀80% 的通用能力,剩下20% 用于定制化开发
前端
CappuccinoRose2 小时前
模块化体系
前端·import·export·es modules
AIDANHANG3 小时前
放开靠时间戳对日志前先核请求ID跨服务传播与采样关联
前端·人工智能
半生过往4 小时前
前端学 Java 课程笔记
java·前端·笔记
广州华水科技5 小时前
2026年单北斗GNSS变形监测系统推荐,破解水库安全监测难题
前端