---
title: "纯前端实现版本更新检测"
url: "https://lerry.me/post/2022/05/check-update-in-frontend"
date: 2022-05-08T02:30:07.176Z
updated: 2026-08-20T17:59:29.373Z
tags:
  - "前端"
  - "Vue.js"
language: zh-CN
---

# 纯前端实现版本更新检测

因为我们的用户会长期保持网页打开状态，有时已经发了新版，他们也不知道，无法使用到最新特性，或者没有看到bug修复，所以最近增加了版本检测功能。

基本原理就是，前端打包时写入当前时间戳到一个文件，作为版本号。前端定时检查版本号是否变化，如果有变化则弹出更新提示。

我们使用的是 Vue.js 框架，使用`vue-cli`作为打包工具。

### 第一步

修改`package.json`文件，在打包完成后写入版本文件

```json
"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build && npm run update-version",
    "lint": "vue-cli-service lint",
    "update-version": "echo `date +%s` > dist/version.txt"
  },
```

### 第二步

编写检测函数，我把这一块代码放在`App.vue`文件里，
使用 `this.hasUpdate` 变量的目的是检测到更新后就不再继续检测。

```js
  created () {
    this.checkVersion()
  },
  methods: {
    showUpdateDialog() {
      this.$confirm('有新版本可用，是否重新加载？', '更新提示', {
        confirmButtonText: '立即刷新',
        cancelButtonText: '稍后再说',
        type: 'warning'
      }).then(() => {
        window.location.reload()
      });
    },
    async checkVersion () {
      const resp = await fetch(`/version.txt?timestamp=${Date.now()}`);
      const versionNow = parseInt(await resp.text());
      if (versionNow) {
        if (this.version) {
          if (versionNow > this.version) {
            this.hasUpdate = true
            this.showUpdateDialog()
          }
        } else {
          this.version = versionNow
        }
      }
      if (!this.hasUpdate) {
        setTimeout(this.checkVersion, 10 * 1000)
      }
    }
  }
```
