Skip to content

generateVersion

在 Vite 构建过程中自动生成版本号,支持多种格式(时间戳、日期、语义化版本、哈希、自定义)和多种输出方式(文件、全局变量、两者兼有)。

导入

typescript
import { generateVersion } from '@meng-xi/vite-plugin'
// 或子模块导入
import { generateVersion } from '@meng-xi/vite-plugin/plugins/generate-version'

快速开始

typescript
import { defineConfig } from 'vite'
import { generateVersion } from '@meng-xi/vite-plugin'

export default defineConfig({
  plugins: [generateVersion()]
})

配置选项

选项类型默认值说明
formatVersionFormat'timestamp'版本号格式
outputTypeOutputType'file'输出类型
outputFilestring'version.json'输出文件路径
defineNamestring'__APP_VERSION__'全局变量名

继承 BasePluginOptionsenabledlogLevelerrorStrategy

高级选项

选项类型默认值说明
customFormatstring-自定义格式模板
semverBasestring'1.0.0'语义化版本基础值
hashLengthnumber8哈希长度(1-32)
prefixstring''版本号前缀
suffixstring''版本号后缀
extraRecord<string, unknown>-附加信息(仅 JSON 文件)

版本号格式

格式说明示例
timestamp时间戳20260203153000
date日期2026.02.03
datetime日期时间2026.02.03.153000
semver语义化版本1.0.0
hash随机哈希a1b2c3d4
custom自定义模板-

输出类型

类型说明
file输出到 JSON 文件
define注入全局变量
both文件和全局变量同时输出

自定义格式占位符

format'custom' 时,customFormat 中可使用以下占位符:

占位符说明示例
{YYYY}四位年份2026
{YY}两位年份26
{MM}两位月份02
{DD}两位日期03
{HH}两位小时15
{mm}两位分钟30
{ss}两位秒数00
{SSS}三位毫秒123
{timestamp}时间戳1738567800
{hash}随机哈希a1b2c3d4
{major}主版本号1
{minor}次版本号0
{patch}补丁版本号0

类型导出

VersionFormat

版本号格式类型:'timestamp' | 'date' | 'datetime' | 'semver' | 'hash' | 'custom'

OutputType

输出类型:'file' | 'define' | 'both'

VersionInfo

版本信息对象,输出到 JSON 文件中的完整数据结构。

属性类型说明
versionstring版本号字符串
buildTimestring构建时间(ISO 8601 格式)
timestampnumber构建时间戳(毫秒)
formatVersionFormat版本号格式
[key]unknown通过 extra 附加的自定义字段

示例

日期格式 + 前缀

typescript
generateVersion({
  format: 'date',
  prefix: 'v'
})
// 输出: v2026.02.03

自定义格式

typescript
generateVersion({
  format: 'custom',
  customFormat: '{YYYY}.{MM}.{DD}-{hash}',
  hashLength: 6
})
// 输出: 2026.02.03-a1b2c3

注入全局变量

typescript
generateVersion({
  outputType: 'define',
  defineName: '__VERSION__'
})

// 代码中使用
console.log(__VERSION__) // '20260203153000'

同时输出文件和注入代码

typescript
generateVersion({
  outputType: 'both',
  outputFile: 'build-info.json',
  defineName: '__BUILD_VERSION__',
  extra: {
    environment: 'production',
    author: 'MengXi Studio'
  }
})

输出文件格式

json
{
  "version": "v2026.02.03-a1b2c3",
  "buildTime": "2026-02-03T15:30:00.000Z",
  "timestamp": 1738567800000,
  "format": "custom",
  "environment": "production",
  "author": "MengXi Studio"
}

注意事项

  • format'custom' 时必须提供 customFormat
  • hashLength 范围为 1-32
  • outputType'define''both' 时,同时注入 defineNamedefineName_INFO 两个全局变量
  • extra 仅包含在 JSON 文件中,不影响版本号字符串
  • 全局变量通过 Vite 的 config 钩子注入,版本文件通过 writeBundle 钩子写入

Released under the MIT License.