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)
相关推荐
搞个锤子哟1 小时前
vue移动端开发长按对话复制功能
前端
AAA阿giao2 小时前
深入理解 JavaScript 的 Array.prototype.map() 方法及其经典陷阱:从原理到面试实战
前端·javascript·面试
excel2 小时前
HBuilderX 配置 adb.exe + 模拟器端口一体化完整指南
前端
拖拉斯旋风3 小时前
与 AI 协作的新范式:以文档为中心的开发实践
前端
dualven_in_csdn3 小时前
【electron】解决CS里的全屏问题
前端·javascript·electron
库克表示3 小时前
MessageChannel-通信机制
前端
拖拉斯旋风3 小时前
深入理解 Ajax:从原理到实战,附大厂高频面试题
前端·ajax
用户4099322502123 小时前
Vue 3响应式系统的底层机制:Proxy如何实现依赖追踪与自动更新?
前端·ai编程·trae
却尘3 小时前
一个"New Chat"按钮,为什么要重构整个架构?
前端·javascript·next.js