使用nodejs脚本生成版本信息json文件 + 监听页面显示和隐藏会触发的visibilitychange(页面显示和隐藏)事件(可以随意使用各种监听方式)

实现原理:

1、使用nodejs编写脚本,获取package.json版本信息,并保存为json文件,存放在构建打包的目录下(比如,public目录)

2、使用页面显示和隐藏会触发的visibilitychange事件,监听页面的显示和隐藏操作,如果页面显示,则请求打包放在dist根目录下的版本信息json文件,对比当前打包版本的version与历史版本信息json文件中version是否一致,如果不一致,则触发浏览器刷新

3、vite打包项目使用.env文件 + import.meta.env保存当前打包变量(webpack打包项目可以使用definePlugin插件 + process.env 保存变量)

1、使用nodejs编写获取package.json版本信息的脚本

 1import { execSync } from 'child_process'  
 2import fs from 'fs'
 3import dotenv from 'dotenv' 
 4import dayjs from 'dayjs'
 5
 6
 7
 8const versionInfoPath = 'versionInfo.json' 
 9const pagePath = 'package.json'
10const publicPath = 'public' 
11const autoPush = false 
12const isVite = true 
13let pageInfo = {}
14
15
16let versionInfoObj = {} 
17
18
19
20if (fs.existsSync(versionInfoPath)) {
21  versionInfoObj = JSON.parse(fs.readFileSync(versionInfoPath).toString())
22}
23
24if (fs.existsSync(pagePath)) {
25  pageInfo = JSON.parse(fs.readFileSync(pagePath).toString())
26}
27
28
29if (pageInfo && versionInfoObj.version === pageInfo.version) {
30  console.warn('\x1B[33m%s\x1b[0m', 'warning: 当前的git版本数据已经存在了!\n')
31} else {
32
33  versionInfoObj = {
34    version: pageInfo.version,
35    name: pageInfo.name,
36    date: dayjs().format('YYYY-MM-DD HH:mm:ss'),
37  }
38  const saveInfoStr = JSON.stringify(versionInfoObj, null, 2)
39  fs.writeFileSync(versionInfoPath, saveInfoStr)
40
41  
42  console.log(
43    '\x1b[32m%s\x1b[0m',
44    `execute success: file address is ${process.cwd()}/${versionInfoPath}\n`,
45  )
46}
47
48
49if (fs.existsSync(publicPath)) {
50  fs.writeFileSync(
51    `${process.cwd()}/${publicPath}/${versionInfoPath}`,
52    fs.readFileSync(versionInfoPath),
53  )
54}
55
56
57if (isVite) {
58  
59
60  const envPath = `${process.cwd()}/.env`
61  
62  const envContent = fs.readFileSync(envPath, {
63    encoding: 'utf-8',
64  })
65
66  
67  const envVariables = dotenv.parse(envContent)
68  const versionInfoStr = JSON.stringify(versionInfoObj)
69  
70  envVariables.VITE_GIT_INFO = versionInfoStr
71
72  
73  const updatedEnvContent = Object.entries(envVariables)
74    .map(([key, value]) => `${key}=${value}`)
75    .join('\n')
76
77  
78  console.log(updatedEnvContent)
79  fs.writeFileSync(envPath, updatedEnvContent, { encoding: 'utf-8' })
80
81  console.log('\x1b[32m%s\x1b[0m', '.env 文件已更新')
82}
83

2、配置执行获取git版本信息脚本命令

 1
 2
 3"scripts": {
 4   "build:git": "npm run get-git && vite build",
 5    "get-git": "node scripts/useNodeGetGitInfo.js",
 6},

3、项目入口JS文件,监听visibilitychange事件

 1 
 2  const gitInfo = import.meta.env.VITE_GIT_INFO
 3  const gitInfoObj = gitInfo && JSON.parse(gitInfo)
 4  if (document.visibilityState === 'hidden') return
 5  fetch(`/versionInfo.json?v=${Date.now()}`)
 6    .then((res) => {
 7      return res.json()
 8    })
 9    .then((data) => {
10      if (data.version !== gitInfoObj.version) {
11        location.reload()
12      }
13    })
个人笔记记录 2021 ~ 2025