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)
相关推荐
山雀~2 分钟前
CSP 安全漏洞修复
前端·网络协议
陌离40 分钟前
Go-Gui:一套 无限接近 现代化UI的 GPU绘制界面组件框架
前端
咚咚咚小柒41 分钟前
【前端】LangChain.js学习
前端·javascript·人工智能·typescript·langchain·vue·ai编程
2401_885885041 小时前
巴林语音通知接口如何对接?系统告警语音API接入教程
android·前端·网络·python·语音识别
java1234_小锋1 小时前
【技术专题】CSS3 网页技术 - CSS3 盒模型
前端·css·css3
计算机魔术师1 小时前
手握芯片、又要吞下开源分发入口,英伟达被盯上了
前端
段一凡-华北理工大学2 小时前
高炉能源系统智能化:热风炉、煤气与极致能效~系列文章07:高炉煤气:产生规律与全厂用户平衡
java·前端·能源
前端架构师-老李2 小时前
HTML与CSS基础第四课—strong、em、b、i 各表示什么
前端·css·html
king王一帅3 小时前
AI 时代一群人在卷笔记软件,我想先把 Markdown 编辑器的底层做好
前端·ai编程·markdown
用户11481867894843 小时前
盲水印:DCT-QIM 从原理到踩坑
前端