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)
相关推荐
灵感__idea7 小时前
Hello 算法:贪心的世界
前端·javascript·算法
GreenTea9 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
killerbasd10 小时前
牧苏苏传 我不装了 4/7
前端·javascript·vue.js
吴声子夜歌10 小时前
ES6——二进制数组详解
前端·ecmascript·es6
码事漫谈11 小时前
手把手带你部署本地模型,让你Token自由(小白专属)
前端·后端
ZC跨境爬虫11 小时前
【爬虫实战对比】Requests vs Scrapy 笔趣阁小说爬虫,从单线程到高效并发的全方位升级
前端·爬虫·scrapy·html
爱上好庆祝11 小时前
svg图片
前端·css·学习·html·css3
王夏奇11 小时前
python中的__all__ 具体用法
java·前端·python
大家的林语冰12 小时前
《前端周刊》尤大开源 Vite+ 全家桶,前端工业革命启动;尤大爆料 Void 云服务新产品,Vite 进军全栈开发;ECMA 源码映射规范......
前端·javascript·vue.js
jiayong2312 小时前
第 8 课:开始引入组合式函数
前端·javascript·学习