前端更新代码自动提示用户更新

1、本文提供了解决前端打包后,提示客户自动更新的功能代码;
2、纯干活,直接复制代码粘贴可用;
3、代码清晰,注释丰富;

代码是基于vue3 + ts,当然其实这个和vue没啥关系的

一、引入判断逻辑

在"@/utils"中新建autoUpdate.ts,在autoUpdate.ts里面写如下代码:

interface Options {
  timer?: number
}

export class Updater {
  oldScript: string[] //存储第一次值也就是script 的hash 信息
  newScript: string[] //获取新的值 也就是新的script 的hash信息
  dispatch: Record<string, Function[]> //小型发布订阅通知用户更新了
  constructor(options?: Options) {
    this.oldScript = []
    this.newScript = []
    this.dispatch = {}
    this.getInitScript().then((): void => {
      this.timing(options?.timer) //轮询
    }) //初始化后轮询比较
  }

  async getInitScript(): Promise<void> {
    const html: string = await this.getHtml()
    this.oldScript = this.parserScript(html)
  }

  async getHtml(): Promise<string> {
    return await fetch(`/`).then(res => res.text()) //读取index html;至于fetch后面是'/'还是其他的路径,取决于你的项目有没有在某个子路径下面(这里不清楚可以单独问我)
  }

  parserScript(html: string): string[] {
    const reg: RegExp = new RegExp(/]*)?>(.*?)<\/script\s*>/gi) //script正则
    return html.match(reg) as string[] //匹配script标签
  }

  //发布订阅通知
  on(key: 'no-update' | 'update', fn: Function) {
    ;(this.dispatch[key] || (this.dispatch[key] = [])).push(fn)
    return this
  }

  compareScript(oldArr: string[], newArr: string[]): void {
    const base: number = oldArr.length
    const arr: string[] = Array.from(new Set(oldArr.concat(newArr)))
    //如果新旧length 一样,说明文件相同,无更新
    if (arr.length === base) {
    //这里我注释了,因为一般情况下,无更新不需要其他处理,需要的话自行放开
      // this.dispatch['no-update'].forEach(fn => {
      //   fn()
      // })
    } else {
      //否则通知更新
      this.dispatch['update'].forEach(fn => {
        fn()
      })
    }
  }

  timing(time: number = 15000): void {
    //轮询
    setInterval(async (): Promise<void> => {
      const newHtml: string = await this.getHtml()
      this.newScript = this.parserScript(newHtml)
      this.compareScript(this.oldScript, this.newScript)
    }, time)
  }
}

二、在main.ts中实例化Updater

在man.ts中引入autoUpdate.ts,并做更新后的处理

// 引入自动更新代码文件
import { Updater } from '@/utils/autoUpdate'

//前端重新部署通知用户刷新网页
const AutoUpdate = new Updater()
AutoUpdate.on('update', () => {
  const result = confirm('您好,当前网站有更新,请点击确定刷新页面再体验')
  if (result) {
    location.reload()
  }
})

童鞋们,复制粘贴即可使用,有问题直接找我!

你可能感兴趣的:(前端)