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)
相关推荐
佛系打工仔13 小时前
绘制K线第二章:背景网格绘制
android·前端·架构
明天好,会的15 小时前
分形生成实验(五):人机协同破局--30万token揭示Actix-web状态管理的微妙边界
运维·服务器·前端
C_心欲无痕15 小时前
nginx - alias 和 root 的区别详解
运维·前端·nginx
我是苏苏18 小时前
Web开发:C#通过ProcessStartInfo动态调用执行Python脚本
java·服务器·前端
无羡仙18 小时前
Vue插槽
前端·vue.js
用户63879947730519 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT19 小时前
React + Ts eslint配置
前端
开始学java19 小时前
useEffect 空依赖 + 定时器 = 闭包陷阱?count 永远停在 1 的坑我踩透了
前端
zerosrat19 小时前
从零实现 React Native(2): 跨平台支持
前端·react native