前端实现发版客户端自动刷新

实现逻辑 编写webpack插件 每次打包生成一个版本Id 然后把生成的Id写成一个json 存放到public文件夹中 前端页面每次跳转的时候 通过get请求获取到这个id 储存到localstorage中 然后和本地的上一次id对比 不一样的就刷新

实现代码

// webpack plugin
const fs = require('fs')
const updateConfigScript = () => {
    let timeStamp = Date.parse(new Date())
    let text = JSON.stringify({ "updateId": timeStamp })
    return text
}
const updateConfig = async () => {
    // 美化代码
    let str = updateConfigScript()
    fs.writeFile(`./public/updateId.json`, str, (err) => {
        if (err) {
            console.error(err);
            console.log('文件写入失败:', err);
        }
        console.log('文件写入成功');
    });
}
class updateBuildAppWebpackPlugin {
    constructor() {
    };
    apply(compiler) {
        compiler.hooks.environment.tap('updateBuildAppWebpackPlugin', () => {
            updateConfig()
        })
    }
}
module.exports = updateBuildAppWebpackPlugin

// 路由跳转时候去对比刷新页面
router.beforeEach((to, from, next) => {
  const res = require("../../public/updateId.json"); // 可替换为git请求 因在本地就没写
  const storageId = localStorage.getItem("updateId");
  if (storageId) {
    if (storageId == res.updateId) {
      next()
    } else {
      next()
      localStorage.setItem("updateId", res.updateId);
      window.location.reload();
    }
  } else {
    next()
    localStorage.setItem("updateId", res.updateId);
    window.location.reload();
  }
})

缺陷: 存在每次跳转都需要去请求 请求过于频繁

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值