封装插件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
配置插件
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
},
}
使用
js
复制代码
import checkVersionNotify from './utils/checkVersionNotify.js'
Vue.use(checkVersionNotify)