-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathvite-plugin-version.ts
More file actions
111 lines (100 loc) · 2.64 KB
/
vite-plugin-version.ts
File metadata and controls
111 lines (100 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* Vite 插件:自动注入版本号和构建日期
*/
import type { Plugin } from 'vite'
import { execSync } from 'child_process'
import { readFileSync } from 'fs'
import { resolve } from 'path'
export interface VersionPluginOptions {
/**
* 是否包含 git commit hash
*/
includeGitHash?: boolean
/**
* 日期格式化函数
*/
formatDate?: (date: Date) => string
}
/**
* 获取 Git commit hash
*/
function getGitHash(): string {
try {
return execSync('git rev-parse --short HEAD').toString().trim()
} catch {
return 'unknown'
}
}
/**
* 获取 Git 分支名
*/
function getGitBranch(): string {
try {
return execSync('git rev-parse --abbrev-ref HEAD').toString().trim()
} catch {
return 'unknown'
}
}
/**
* 从 package.json 读取版本号
*/
function getPackageVersion(): string {
try {
const packageJson = JSON.parse(
readFileSync(resolve(process.cwd(), 'package.json'), 'utf-8')
)
return packageJson.version || '0.0.0'
} catch {
return '0.0.0'
}
}
/**
* 格式化日期
*/
function formatDate(date: Date): string {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
/**
* 格式化日期时间
*/
function formatDateTime(date: Date): string {
const dateStr = formatDate(date)
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
const seconds = String(date.getSeconds()).padStart(2, '0')
return `${dateStr} ${hours}:${minutes}:${seconds}`
}
/**
* 创建版本信息插件
*/
export default function versionPlugin(options: VersionPluginOptions = {}): Plugin {
const { includeGitHash = true, formatDate: customFormatDate } = options
return {
name: 'vite-plugin-version',
config() {
const now = new Date()
const version = getPackageVersion()
const buildDate = customFormatDate ? customFormatDate(now) : formatDate(now)
const buildTime = formatDateTime(now)
const gitHash = includeGitHash ? getGitHash() : ''
const gitBranch = getGitBranch()
// 构建完整版本号
let fullVersion = version
if (includeGitHash && gitHash !== 'unknown') {
fullVersion = `${version}+${gitHash}`
}
return {
define: {
__APP_VERSION__: JSON.stringify(fullVersion),
__BUILD_DATE__: JSON.stringify(buildDate),
__BUILD_TIME__: JSON.stringify(buildTime),
__GIT_HASH__: JSON.stringify(gitHash),
__GIT_BRANCH__: JSON.stringify(gitBranch),
},
}
},
}
}