@minto-ai/version-polling
v1.0.31
Published
实时检测是否发布新版本
Readme
@minto-ai/version-polling
@minto-ai/version-polling 是一个用于实时检测线上环境版本更新的轻量级工具。它支持通过 HTML 文件的 ETag/Last-Modified 或 JSON 文件的版本号字段来检测更新。
特性
- 🚀 零依赖:轻量级设计,不依赖任何第三方库(Worker 内部实现)。
- 🔄 自动轮询:基于 Web Worker 的定时轮询,不阻塞主线程。
- 👁️ 智能暂停:当页面不可见时自动暂停轮询,节省资源;页面可见时自动恢复。
- 📦 双模式支持:
- HTML 模式:检测 HTML 文件的
ETag或Last-Modified响应头变化。 - JSON 模式:检测
manifest.json或其他 JSON 文件中的version字段变化(需符合 SemVer 规范)。
- HTML 模式:检测 HTML 文件的
安装
pnpm install @minto-ai/version-polling使用示例
基础用法(检测 HTML)
默认情况下,工具会检测当前页面的 HTML 文件。
import { createVersionPolling } from '@minto-ai/version-polling'
const versionPolling = createVersionPolling({
pollingInterval: 60, // 轮询间隔,单位秒
})
versionPolling.on('update', () => {
// 发现新版本,可以提示用户刷新页面
if (confirm('发现新版本,是否刷新?')) {
window.location.reload()
}
})进阶用法(检测 JSON)
如果你使用 manifest.json 或专门的版本文件来管理版本号。
import { createVersionPolling } from '@minto-ai/version-polling'
const versionPolling = createVersionPolling({
// 指定检测的 JSON 文件路径
fileUrl: 'manifest.json',
pollingInterval: 30,
})
versionPolling.on('update', () => {
console.log('检测到新版本发布!')
})API
createVersionPolling(options)
创建并返回一个版本轮询实例。
参数 options
| 属性 | 类型 | 默认值 | 说明 |
| ----------------- | -------- | -------------------------- | ------------------------------------------------------------------------------------------- |
| pollingInterval | number | 60 | 轮询间隔时间,单位为秒。 |
| fileUrl | string | window.location.pathname | 目标文件地址。可以是 HTML 路径或 JSON 文件路径。工具会自动根据后缀(.json)判断检测模式。 |
实例方法
on(eventName, callback)
监听事件。
- 事件名:
'update' - 回调参数: 无
emit(eventName, data?)
手动触发事件(通常不需要手动调用)。
