Skip to content

generateVersion

在 Vite 构建过程中自动生成版本号,支持文件输出和全局变量注入。

快速开始

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

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

配置选项

选项类型默认值说明
formatVersionFormat'timestamp'版本号格式
customFormatstring-自定义格式模板
semverBasestring'1.0.0'语义化版本基础值
autoIncrementbooleanfalse自动递增补丁版本号
outputTypeOutputType'file'输出类型
outputFilestring'version.json'输出文件路径
defineNamestring'__APP_VERSION__'全局变量名
hashLengthnumber8哈希长度(1-32)
prefixstring''版本号前缀
suffixstring''版本号后缀
extraRecord<string, unknown>-附加信息(仅 JSON 文件)
enabledbooleantrue启用插件
verbosebooleantrue显示详细日志
errorStrategy'throw' | 'log' | 'ignore''throw'错误处理策略

版本号格式

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

输出类型

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

自定义格式占位符

占位符说明示例
{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

示例

日期格式 + 前缀

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 文件中,不影响版本号字符串

Released under the MIT License.