1+ import type { Plugin } from 'vite'
2+ import { readFileSync , existsSync , writeFileSync } from 'fs'
3+ import { resolve } from 'path'
4+ import fs from 'fs'
5+
6+ // 从 Markdown 文件中提取版本信息
7+ function extractVersionFromMarkdown ( filePath : string ) : string | null {
8+ if ( ! existsSync ( filePath ) ) return null
9+
10+ try {
11+ const content = readFileSync ( filePath , 'utf-8' )
12+ const frontmatterMatch = content . match ( / ^ - - - \s * \n ( [ \s \S ] * ?) \n - - - \s * \n / )
13+
14+ if ( frontmatterMatch ) {
15+ const frontmatter = frontmatterMatch [ 1 ]
16+ const versionMatch = frontmatter . match ( / v e r s i o n : \s * ( [ ' " ] ? ) ( [ ^ ' " \n ] + ) \1/ )
17+
18+ if ( versionMatch ) {
19+ return versionMatch [ 2 ] . trim ( )
20+ }
21+ }
22+ } catch ( e ) {
23+ console . warn ( `Failed to read file ${ filePath } :` , e )
24+ }
25+
26+ return null
27+ }
28+
29+ // 扫描组件文档目录,提取版本信息
30+ function scanComponentVersions ( ) : Record < string , string > {
31+ const versionData : Record < string , string > = { }
32+ const componentDir = resolve ( __dirname , '../../component' )
33+
34+ if ( ! existsSync ( componentDir ) ) {
35+ console . warn ( 'Component directory not found:' , componentDir )
36+ return versionData
37+ }
38+
39+ try {
40+ const files = fs . readdirSync ( componentDir ) . filter ( ( file : string ) => file . endsWith ( '.md' ) )
41+
42+ files . forEach ( ( filename : string ) => {
43+ const filePath = resolve ( componentDir , filename )
44+ const version = extractVersionFromMarkdown ( filePath )
45+
46+ if ( version ) {
47+ const path = `/component/${ filename . replace ( '.md' , '' ) } `
48+ versionData [ path ] = version
49+ console . log ( `✅ Found version info in ${ filename } :` , version )
50+ }
51+ } )
52+ } catch ( e ) {
53+ console . warn ( 'Failed to scan component directory:' , e )
54+ }
55+
56+ return versionData
57+ }
58+
59+ // 生成版本数据文件
60+ function generateVersionData ( ) : string {
61+ const versionData = scanComponentVersions ( )
62+
63+ return `// 自动生成的版本数据
64+ // 此文件由插件自动生成,请勿手动修改
65+ // 如需修改版本信息,请在对应的 Markdown 文件 frontmatter 中修改
66+
67+ export const versionData = ${ JSON . stringify ( versionData , null , 2 ) }
68+ `
69+ }
70+
71+ export function VersionBadgePlugin ( ) : Plugin {
72+ return {
73+ name : 'version-badge' ,
74+ configResolved ( ) {
75+ // 在配置解析后生成版本数据
76+ try {
77+ const versionDataContent = generateVersionData ( )
78+ const outputPath = resolve ( __dirname , '../config/version-data.ts' )
79+
80+ writeFileSync ( outputPath , versionDataContent , 'utf-8' )
81+ console . log ( '✅ Version data generated successfully' )
82+ } catch ( e ) {
83+ console . error ( '❌ Failed to generate version data:' , e )
84+ }
85+ }
86+ }
87+ }
0 commit comments