npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@xtliyq/vite-plugin-version

v0.1.0

Published

A Vite plugin that injects build version and build time into your frontend app.

Readme

@xtliyq/vite-plugin-version

一个为前端项目注入构建版本号构建时间的 Vite 插件。
支持四种注入方式:全局常量、虚拟模块、HTML <meta> 标签、HTML window 变量。
内置版本更新检测功能,发现新版本时自动通知用户刷新页面。

功能特性

  • 📦 多种版本策略:读取 package.json、追加 Git 哈希、使用 Git 标签或完全自定义
  • 🕐 构建时间注入:格式化时间字符串和 Unix 时间戳
  • 🔧 全局 define 常量:编译时替换(__APP_VERSION__ 等)
  • 📦 虚拟模块import { version } from 'virtual:version'
  • 🏷️ HTML meta 标签<meta name="app-version" content="...">
  • 🪟 HTML script 变量:全局可访问的 window.__APP_VERSION__
  • 🔔 版本更新检测:事件驱动(标签页焦点 + 可见性)+ 可选定时兜底,发现新版本自动通知

安装

npm install @xtliyq/vite-plugin-version -D
# 或
pnpm add @xtliyq/vite-plugin-version -D

使用

// vite.config.ts
import { defineConfig } from 'vite'
import vitePluginVersion from '@xtliyq/vite-plugin-version'

export default defineConfig({
  plugins: [
    vitePluginVersion({
      versionStrategy: 'git-hash',      // 开发模式追加 Git 短哈希
      appendHashInDev: true,
      timeFormat: 'YYYY-MM-DD HH:mm:ss',
      html: {
        meta: true,
        script: true,
      },
      checker: {
        checkOnFocus: true,             // 标签页获焦时检查(推荐)
        checkOnVisible: true,           // 页面可见性变化时检查(推荐)
        interval: 10 * 60_000,          // 10 分钟定时兜底
      },
    }),
  ],
})

四种注入方式

1. 全局 define 常量(编译时替换)

// 无需 import,直接使用(TypeScript 用户请参考下方类型声明配置)
console.log(__APP_VERSION__)          // "1.0.0+a3b4c5d"
console.log(__APP_BUILD_TIME__)       // "2026-03-04 10:30:00"
console.log(__APP_BUILD_TIMESTAMP__)  // 1741055400000
console.log(__APP_NAME__)             // "my-app"
console.log(__APP_GIT_HASH__)         // "a3b4c5d"(仅 git-hash 策略)

env.d.tsvite-env.d.ts 中添加类型声明:

declare const __APP_VERSION__: string
declare const __APP_BUILD_TIME__: string
declare const __APP_BUILD_TIMESTAMP__: number
declare const __APP_NAME__: string
declare const __APP_GIT_HASH__: string | undefined

2. 虚拟模块

import { version, buildTime, buildTimestamp, name, gitHash } from 'virtual:version'
// 或使用别名
import versionInfo from '~version'

console.log(versionInfo.version)   // "1.0.0+a3b4c5d"
console.log(versionInfo.buildTime) // "2026-03-04 10:30:00"

TypeScript 类型支持,在 tsconfig.json 中添加:

{
  "compilerOptions": {
    "types": ["@xtliyq/vite-plugin-version/client"]
  }
}

或在 env.d.ts 中使用三斜线引用:

/// <reference types="@xtliyq/vite-plugin-version/client" />

3. HTML <meta> 标签

构建和开发时自动注入到 <head>

<meta name="app-version" content="1.0.0+a3b4c5d">
<meta name="app-build-time" content="2026-03-04 10:30:00">
<meta name="app-name" content="my-app">

4. HTML <script> window 变量

<script> 标签形式注入到 <head> 最前端,页面加载即可访问:

<script>
  window.__APP_VERSION__ = "1.0.0+a3b4c5d";
  window.__APP_BUILD_TIME__ = "2026-03-04 10:30:00";
  window.__APP_BUILD_TIMESTAMP__ = 1741055400000;
  window.__APP_NAME__ = "my-app";
  window.__APP_GIT_HASH__ = "a3b4c5d";
</script>

版本更新检测

插件构建时会在 dist/ 目录自动生成 version.json,前端通过 virtual:version/checker 虚拟模块进行检测。

检测策略(事件驱动,无性能损耗):

| 触发时机 | 说明 | 性能 | |---------|------|------| | 标签页获得焦点 | 用户切回标签页的第一时间 | ⭐ 无轮询 | | 页面从后台变为可见 | 手机切回浏览器、切换标签页 | ⭐ 无轮询 | | 定时兜底(可选)| 用户长时间不切换标签页时的保底 | 可配置间隔 |

在项目入口文件中引入:

// main.ts
import { startVersionChecker } from 'virtual:version/checker'

startVersionChecker({
  interval: 10 * 60_000,   // 10 分钟定时兜底(0 表示禁用)
  onUpdate(newInfo) {
    // 可接入任何 UI 框架的通知组件(Element Plus、Ant Design、Naive UI 等)
    if (confirm(`发现新版本 ${newInfo.version},是否立即刷新?`)) {
      window.location.reload()
    }
  },
})

与 Element Plus 通知组件配合使用:

import { ElNotification } from 'element-plus'
import { startVersionChecker } from 'virtual:version/checker'

startVersionChecker({
  onUpdate(newInfo) {
    ElNotification({
      title: '发现新版本',
      message: `版本 ${newInfo.version} 已发布(${newInfo.buildTime}),点击刷新以获得最新体验`,
      type: 'info',
      duration: 0,   // 不自动关闭
      onClick: () => window.location.reload(),
    })
  },
})

自动刷新模式(无需用户确认):

startVersionChecker({
  autoRefresh: true,        // 发现新版本立即刷新
  onUpdate(newInfo) {
    console.log(`检测到新版本 ${newInfo.version},正在刷新...`)
  },
})

手动停止检测:

import { startVersionChecker, stopVersionChecker } from 'virtual:version/checker'

// startVersionChecker 返回 stop 函数
const stop = startVersionChecker({ onUpdate: () => {} })

// 需要时停止检测(例如在组件卸载时)
stop()
// 或直接调用
stopVersionChecker()

version.json 文件内容示例:

{
  "version": "1.0.0",
  "buildTime": "2026-03-04 10:30:00",
  "buildTimestamp": 1741055400000,
  "name": "my-app"
}

提示: 开发模式(vite dev)不会生成 version.json,检测器不会触发任何更新通知,无需额外处理。

配置项

| 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | versionStrategy | 'package' \| 'git-hash' \| 'git-tag' \| 'custom' | 'git-hash' | 版本号解析策略 | | version | string | — | 自定义版本号,仅 'custom' 策略生效 | | gitHashLength | number | 7 | Git 短哈希的长度 | | appendHashInDev | boolean | true | 仅在开发(serve)模式追加 Git 哈希 | | timeFormat | string | 'YYYY-MM-DD HH:mm:ss' | 构建时间格式,支持占位符:YYYY MM DD HH mm ss | | buildTime | string \| Date | 当前时间 | 覆盖构建时间 | | ifDefine | boolean | true | 是否注入全局 define 常量 | | definePrefix | string | '__APP_' | 全局常量的前缀 | | ifVirtual | boolean | true | 是否提供虚拟模块 virtual:version / ~version | | html | HtmlInjectOptions \| false | {} | HTML 注入配置,设为 false 可完全禁用 | | checker | CheckerOptions \| false | {} | 版本检测配置,设为 false 可完全禁用(不生成 version.json) |

HtmlInjectOptions

| 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | meta | boolean | true | 是否注入 <meta> 标签 | | script | boolean | true | 是否注入包含 window 变量的 <script> | | scriptPrefix | string | '__APP_' | window 变量的前缀 |

CheckerOptions

| 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | versionJsonPath | string | '/version.json' | version.json 的请求路径 | | checkOnFocus | boolean | true | 标签页获得焦点时检查 | | checkOnVisible | boolean | true | 页面可见性变化时检查 | | interval | number | 600000 | 定时兜底间隔(毫秒),0 表示禁用 | | onUpdate | (info: CheckerUpdateInfo) => void | — | 发现新版本时的回调 | | autoRefresh | boolean | false | 发现新版本时自动刷新页面 |

版本策略说明

| 策略 | 开发模式输出 | 生产构建输出 | 备注 | |------|------------|------------|------| | package | 1.0.0 | 1.0.0 | 始终读取 package.json | | git-hash | 1.0.0+a3b4c5d | 1.0.0 | 开发模式追加哈希(appendHashInDev: true 时) | | git-tag | v1.0.0-3-ga3b4c5d | v1.0.0-3-ga3b4c5d | 使用 git describe --tags --always | | custom | 自定义字符串 | 自定义字符串 | 直接使用 version 选项 |

提示: 当 Git 不可用时(如无 Git 环境的 CI、浅克隆等),插件会自动降级使用 package.json 中的版本号,不会抛出错误。

许可证

MIT