前端每次改动重新部署项目的时候,如果用户一直停留在页面上并未刷新使用,可能会存在数据问题或者一些其他bug,因此,当前端项目更新后,需要提醒用户去重新刷新页面后使用。
第一步 再build文件下创建version-webpack-plugin.js文件,或者同目录下创建
const fs = require('fs')
class VersionPlugin {
apply (compiler) {
compiler.plugin('done', function () {
const outputPath = compiler.outputPath
const versionFile = outputPath + '/version.json'
const timestamp = Date.now()
const content = `{"version": "${timestamp}"}`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
fs.writeFileSync(versionFile, content, {
encoding: 'utf8',
flag: 'w'
})
})
}
}
module.exports = { VersionPlugin }
第二步 在webpack.prod.conf.js文件中引入
const { VersionPlugin } = require('./version-webpack-plugin');
// ...
plugins: [
..., // 其他配置代码
new VersionPlugin()
]
这样打包就会在dist文件下生成version.json文件
第三步 我这边是在路由上监听是否有更新
process.env.NODE_ENV !== 'development' && Vue.prototype.$axios.get(window.location.href.split('/#/')[0] + '/version.json?v=' + Date.now()).then(rsp => {
let latestVersion = localStorage.getItem('latestVersion');
let version = rsp.data.version;
if (version) {
if (latestVersion !== version) {
MessageBox.confirm('有版本更新,是否刷新?', '版本更新', {
confirmButtonText: '更新',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
localStorage.setItem('latestVersion', version);
window.location.reload();
});
}
}
});
完成😄