@meng-xi/vite-plugin 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README-en.md +49 -775
  2. package/README.md +46 -770
  3. package/dist/common/format/index.cjs +1 -1
  4. package/dist/common/format/index.d.cts +1 -130
  5. package/dist/common/format/index.d.mts +1 -130
  6. package/dist/common/format/index.d.ts +1 -130
  7. package/dist/common/format/index.mjs +1 -1
  8. package/dist/common/fs/index.cjs +1 -1
  9. package/dist/common/fs/index.d.cts +1 -89
  10. package/dist/common/fs/index.d.mts +1 -89
  11. package/dist/common/fs/index.d.ts +1 -89
  12. package/dist/common/fs/index.mjs +1 -1
  13. package/dist/common/html/index.cjs +2 -2
  14. package/dist/common/html/index.d.cts +19 -81
  15. package/dist/common/html/index.d.mts +19 -81
  16. package/dist/common/html/index.d.ts +19 -81
  17. package/dist/common/html/index.mjs +2 -2
  18. package/dist/common/index.cjs +1 -1
  19. package/dist/common/index.d.cts +7 -8
  20. package/dist/common/index.d.mts +7 -8
  21. package/dist/common/index.d.ts +7 -8
  22. package/dist/common/index.mjs +1 -1
  23. package/dist/common/script/index.cjs +1 -1
  24. package/dist/common/script/index.d.cts +1 -44
  25. package/dist/common/script/index.d.mts +1 -44
  26. package/dist/common/script/index.d.ts +1 -44
  27. package/dist/common/script/index.mjs +1 -1
  28. package/dist/common/ui/index.cjs +1 -0
  29. package/dist/common/ui/index.d.cts +22 -0
  30. package/dist/common/ui/index.d.mts +22 -0
  31. package/dist/common/ui/index.d.ts +22 -0
  32. package/dist/common/ui/index.mjs +1 -0
  33. package/dist/common/validation/index.cjs +1 -1
  34. package/dist/common/validation/index.d.cts +2 -79
  35. package/dist/common/validation/index.d.mts +2 -79
  36. package/dist/common/validation/index.d.ts +2 -79
  37. package/dist/common/validation/index.mjs +1 -1
  38. package/dist/factory/index.cjs +1 -1
  39. package/dist/factory/index.d.cts +1 -1
  40. package/dist/factory/index.d.mts +1 -1
  41. package/dist/factory/index.d.ts +1 -1
  42. package/dist/factory/index.mjs +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.d.cts +12 -10
  45. package/dist/index.d.mts +12 -10
  46. package/dist/index.d.ts +12 -10
  47. package/dist/index.mjs +1 -1
  48. package/dist/logger/index.d.cts +92 -1
  49. package/dist/logger/index.d.mts +92 -1
  50. package/dist/logger/index.d.ts +92 -1
  51. package/dist/plugins/autoImport/index.cjs +17 -0
  52. package/dist/plugins/autoImport/index.d.cts +291 -0
  53. package/dist/plugins/autoImport/index.d.mts +291 -0
  54. package/dist/plugins/autoImport/index.d.ts +291 -0
  55. package/dist/plugins/autoImport/index.mjs +17 -0
  56. package/dist/plugins/buildProgress/index.cjs +2 -2
  57. package/dist/plugins/buildProgress/index.d.cts +1 -1
  58. package/dist/plugins/buildProgress/index.d.mts +1 -1
  59. package/dist/plugins/buildProgress/index.d.ts +1 -1
  60. package/dist/plugins/buildProgress/index.mjs +2 -2
  61. package/dist/plugins/bundleAnalyzer/index.cjs +11 -11
  62. package/dist/plugins/bundleAnalyzer/index.d.cts +1 -1
  63. package/dist/plugins/bundleAnalyzer/index.d.mts +1 -1
  64. package/dist/plugins/bundleAnalyzer/index.d.ts +1 -1
  65. package/dist/plugins/bundleAnalyzer/index.mjs +18 -18
  66. package/dist/plugins/compressAssets/index.cjs +1 -1
  67. package/dist/plugins/compressAssets/index.d.cts +1 -1
  68. package/dist/plugins/compressAssets/index.d.mts +1 -1
  69. package/dist/plugins/compressAssets/index.d.ts +1 -1
  70. package/dist/plugins/compressAssets/index.mjs +1 -1
  71. package/dist/plugins/copyFile/index.cjs +1 -1
  72. package/dist/plugins/copyFile/index.d.cts +21 -3
  73. package/dist/plugins/copyFile/index.d.mts +21 -3
  74. package/dist/plugins/copyFile/index.d.ts +21 -3
  75. package/dist/plugins/copyFile/index.mjs +1 -1
  76. package/dist/plugins/envGuard/index.cjs +67 -0
  77. package/dist/plugins/envGuard/index.d.cts +255 -0
  78. package/dist/plugins/envGuard/index.d.mts +255 -0
  79. package/dist/plugins/envGuard/index.d.ts +255 -0
  80. package/dist/plugins/envGuard/index.mjs +67 -0
  81. package/dist/plugins/faviconManager/index.cjs +1 -1
  82. package/dist/plugins/faviconManager/index.d.cts +44 -6
  83. package/dist/plugins/faviconManager/index.d.mts +44 -6
  84. package/dist/plugins/faviconManager/index.d.ts +44 -6
  85. package/dist/plugins/faviconManager/index.mjs +1 -1
  86. package/dist/plugins/generateRouter/index.cjs +4 -4
  87. package/dist/plugins/generateRouter/index.d.cts +62 -15
  88. package/dist/plugins/generateRouter/index.d.mts +62 -15
  89. package/dist/plugins/generateRouter/index.d.ts +62 -15
  90. package/dist/plugins/generateRouter/index.mjs +4 -4
  91. package/dist/plugins/generateVersion/index.cjs +1 -1
  92. package/dist/plugins/generateVersion/index.d.cts +13 -1
  93. package/dist/plugins/generateVersion/index.d.mts +13 -1
  94. package/dist/plugins/generateVersion/index.d.ts +13 -1
  95. package/dist/plugins/generateVersion/index.mjs +1 -1
  96. package/dist/plugins/htmlInject/index.cjs +7 -7
  97. package/dist/plugins/htmlInject/index.d.cts +50 -195
  98. package/dist/plugins/htmlInject/index.d.mts +50 -195
  99. package/dist/plugins/htmlInject/index.d.ts +50 -195
  100. package/dist/plugins/htmlInject/index.mjs +7 -7
  101. package/dist/plugins/index.cjs +1 -1
  102. package/dist/plugins/index.d.cts +5 -2
  103. package/dist/plugins/index.d.mts +5 -2
  104. package/dist/plugins/index.d.ts +5 -2
  105. package/dist/plugins/index.mjs +1 -1
  106. package/dist/plugins/loadingManager/index.cjs +26 -26
  107. package/dist/plugins/loadingManager/index.d.cts +1 -1
  108. package/dist/plugins/loadingManager/index.d.mts +1 -1
  109. package/dist/plugins/loadingManager/index.d.ts +1 -1
  110. package/dist/plugins/loadingManager/index.mjs +11 -11
  111. package/dist/plugins/versionUpdateChecker/index.cjs +1 -1
  112. package/dist/plugins/versionUpdateChecker/index.d.cts +1 -1
  113. package/dist/plugins/versionUpdateChecker/index.d.mts +1 -1
  114. package/dist/plugins/versionUpdateChecker/index.d.ts +1 -1
  115. package/dist/plugins/versionUpdateChecker/index.mjs +1 -1
  116. package/dist/shared/vite-plugin.B8FuZce1.d.cts +45 -0
  117. package/dist/shared/vite-plugin.B8FuZce1.d.mts +45 -0
  118. package/dist/shared/vite-plugin.B8FuZce1.d.ts +45 -0
  119. package/dist/shared/vite-plugin.BI9taN75.d.cts +122 -0
  120. package/dist/shared/vite-plugin.BI9taN75.d.mts +122 -0
  121. package/dist/shared/vite-plugin.BI9taN75.d.ts +122 -0
  122. package/dist/shared/vite-plugin.BPFqtmWa.mjs +1 -0
  123. package/dist/shared/vite-plugin.CnOy46d3.cjs +1 -0
  124. package/package.json +16 -16
  125. package/dist/common/compress/index.cjs +0 -1
  126. package/dist/common/compress/index.d.cts +0 -23
  127. package/dist/common/compress/index.d.mts +0 -23
  128. package/dist/common/compress/index.d.ts +0 -23
  129. package/dist/common/compress/index.mjs +0 -1
  130. package/dist/common/object/index.cjs +0 -1
  131. package/dist/common/object/index.d.cts +0 -30
  132. package/dist/common/object/index.d.mts +0 -30
  133. package/dist/common/object/index.d.ts +0 -30
  134. package/dist/common/object/index.mjs +0 -1
  135. package/dist/common/path/index.cjs +0 -1
  136. package/dist/common/path/index.d.cts +0 -22
  137. package/dist/common/path/index.d.mts +0 -22
  138. package/dist/common/path/index.d.ts +0 -22
  139. package/dist/common/path/index.mjs +0 -1
  140. package/dist/shared/vite-plugin.CLr0ttuO.d.cts +0 -135
  141. package/dist/shared/vite-plugin.CLr0ttuO.d.mts +0 -135
  142. package/dist/shared/vite-plugin.CLr0ttuO.d.ts +0 -135
package/README-en.md CHANGED
@@ -1,4 +1,4 @@
1
- **English** | [中文](./README.md)
1
+ [中文](./README.md) | **English**
2
2
 
3
3
  <div align="center">
4
4
  <a href="https://github.com/MengXi-Studio/vite-plugin">
@@ -6,7 +6,7 @@
6
6
  </a>
7
7
  <br>
8
8
  <h1>@meng-xi/vite-plugin</h1>
9
- <p>A toolkit providing practical plugins for Vite, also a complete plugin development framework</p>
9
+ <p>A practical Vite plugin toolkit and a complete plugin development framework</p>
10
10
 
11
11
  [![license](https://img.shields.io/github/license/MengXi-Studio/vite-plugin.svg)](LICENSE) [![npm](https://img.shields.io/npm/v/@meng-xi/vite-plugin?color=blue)](https://www.npmjs.com/package/@meng-xi/vite-plugin)
12
12
  ![npm](https://img.shields.io/npm/dt/@meng-xi/vite-plugin?color=green)
@@ -15,20 +15,14 @@
15
15
 
16
16
  ## Features
17
17
 
18
- - **Ready to Use** - Provides 10 practical plugins covering build progress display, build artifact analysis & compression, file copying, router generation, version management, version update checking, HTML injection,
19
- icon injection, and global Loading state management
20
- - **Plugin Development Framework** - Exports core components like BasePlugin, Logger, Validator for building custom Vite plugins that follow conventions
21
- - **Common Utility Library** - Built-in Common module providing reusable utility functions for formatting, file system, compression, path handling, HTML injection, object operations, script generation, and parameter
22
- validation
23
- - **Complete Lifecycle** - Supports initialization, config resolution, destroy lifecycle management with automatic hook composition
24
- - **Type Safe** - Complete TypeScript type definitions with configuration validators ensuring parameter correctness
25
- - **Flexible Configuration** - All plugins support detailed configuration to meet diverse scenario requirements
26
- - **Safe Execution** - Built-in error handling strategies (throw / log / ignore) for unified exception management
18
+ - **Ready to Use** - 12 practical plugins covering auto-import, build progress, bundle analysis & compression, file copying, environment variable validation, route generation, version management, HTML injection, favicon
19
+ management, global Loading, and more
20
+ - **Plugin Development Framework** - Exports core components like BasePlugin, Logger, and Validator to quickly build custom Vite plugins
21
+ - **Common Utility Library** - Built-in Common utility modules supporting on-demand sub-path imports
22
+ - **Type Safe** - Complete TypeScript type definitions with configuration validators
27
23
  - **On-demand Import** - Supports sub-path exports to reduce bundle size
28
24
 
29
- ## Documentation
30
-
31
- View full documentation: [https://mengxi-studio.github.io/vite-plugin/](https://mengxi-studio.github.io/vite-plugin/)
25
+ 📖 **Full Documentation: [https://mengxi-studio.github.io/vite-plugin/](https://mengxi-studio.github.io/vite-plugin/)**
32
26
 
33
27
  ## Installation
34
28
 
@@ -45,554 +39,48 @@ pnpm add @meng-xi/vite-plugin -D
45
39
 
46
40
  ## Quick Start
47
41
 
48
- ### Using Built-in Plugins
49
-
50
42
  ```typescript
51
43
  import { defineConfig } from 'vite'
52
- import { buildProgress, bundleAnalyzer, compressAssets, copyFile, generateRouter, generateVersion, versionUpdateChecker, htmlInject, faviconManager, loadingManager } from '@meng-xi/vite-plugin'
44
+ import { buildProgress, bundleAnalyzer, compressAssets, copyFile, envGuard, generateRouter, generateVersion, versionUpdateChecker, htmlInject, faviconManager, loadingManager, autoImport } from '@meng-xi/vite-plugin'
53
45
 
54
46
  export default defineConfig({
55
47
  plugins: [
48
+ autoImport({ imports: { vue: ['ref', 'reactive', 'computed'] }, dts: 'src/auto-imports.d.ts' }),
56
49
  buildProgress(),
57
- bundleAnalyzer({ outputFormat: 'both', sizeThreshold: 200 }),
50
+ bundleAnalyzer({ outputFormat: 'both' }),
58
51
  compressAssets({ algorithm: 'gzip' }),
59
52
  copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' }),
60
- generateRouter({ pagesJsonPath: 'src/pages.json', outputPath: 'src/router.config.ts' }),
53
+ envGuard({ rules: { VITE_API_URL: { type: 'string', required: true } } }),
54
+ generateRouter(),
61
55
  generateVersion({ format: 'datetime', outputType: 'both' }),
62
56
  versionUpdateChecker(),
63
- htmlInject({
64
- rules: [{ id: 'meta-description', content: '<meta name="description" content="My App">', position: 'head-end' }]
65
- }),
57
+ htmlInject({ rules: [{ id: 'meta', content: '<meta name="description" content="My App">', position: 'head-end' }] }),
66
58
  faviconManager('/assets'),
67
59
  loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
68
60
  ]
69
61
  })
70
62
  ```
71
63
 
72
- ### Accessing Plugin Instance
73
-
74
- All built-in plugins return an object with a `pluginInstance` property for accessing internal state:
75
-
76
- ```typescript
77
- import type { PluginWithInstance } from '@meng-xi/vite-plugin/factory'
78
- import type { GenerateRouterOptions } from '@meng-xi/vite-plugin'
79
-
80
- const routerPlugin = generateRouter({ watch: true }) as PluginWithInstance<GenerateRouterOptions>
81
- console.log(routerPlugin.pluginInstance?.options)
82
- ```
83
-
84
64
  ## Built-in Plugins
85
65
 
86
- | Plugin | Description |
87
- | -------------------- | -------------------------------------------------------------------------------------------------------------------- |
88
- | buildProgress | Real-time build progress bar in terminal, supports bar / spinner / minimal |
89
- | bundleAnalyzer | Build artifact size analysis with JSON/HTML reports, gzip calculation, threshold alerts, and build comparison |
90
- | compressAssets | Compress build artifacts with gzip / brotli / both, concurrent compression and statistics report |
91
- | copyFile | Copy files or directories after build, supports incremental copying |
92
- | generateRouter | Auto-generate router config from pages.json (uni-app) |
93
- | generateVersion | Auto-generate version numbers, supports file output and global variable injection |
94
- | versionUpdateChecker | Runtime version update checking with multiple prompt styles and custom callbacks |
95
- | htmlInject | HTML content injection with multiple positions, conditional injection, template variables, and security filtering |
96
- | faviconManager | Manage website favicon links injection and file copying, supports string shorthand config |
97
- | loadingManager | Global Loading state management with request interception, debounce, transition animations, and white-screen Loading |
98
-
99
- ---
100
-
101
- ### buildProgress
102
-
103
- Display real-time build progress bar in terminal during Vite build, supporting three display formats.
104
-
105
- **Progress calculation logic:**
106
-
107
- 1. config phase (5%) → resolve phase (10%) → transform phase (15%-85%, by module conversion ratio) → bundle phase (+10%) → write phase (+5%) → done (100%)
108
- 2. Non-TTY terminal environments (e.g. CI/CD) automatically degrade to log output mode
109
-
110
- | Option | Type | Default | Description |
111
- | --------------- | ------------------------------------- | ------- | ---------------------------------------------------- |
112
- | width | `number` | `30` | Progress bar width (characters) |
113
- | format | `'bar'` \| `'spinner'` \| `'minimal'` | `'bar'` | Progress bar display format |
114
- | completeChar | `string` | `'█'` | Fill character for completed portion |
115
- | incompleteChar | `string` | `'░'` | Fill character for incomplete portion |
116
- | clearOnComplete | `boolean` | `true` | Whether to clear progress bar on build completion |
117
- | showModuleName | `boolean` | `true` | Whether to show the currently processing module name |
118
- | theme | `ProgressTheme` | - | Custom color theme |
119
-
120
- **ProgressTheme**
121
-
122
- | Property | Type | Description |
123
- | --------------- | -------------------------- | ------------------------ |
124
- | completeColor | `(text: string) => string` | Completed portion color |
125
- | incompleteColor | `(text: string) => string` | Incomplete portion color |
126
- | percentageColor | `(text: string) => string` | Percentage number color |
127
- | phaseColor | `(text: string) => string` | Phase label color |
128
- | moduleColor | `(text: string) => string` | Module name color |
129
-
130
- ```typescript
131
- buildProgress()
132
- buildProgress({ format: 'spinner' })
133
- buildProgress({ format: 'minimal' })
134
- buildProgress({ width: 40, completeChar: '■', incompleteChar: '□', clearOnComplete: false })
135
- buildProgress({
136
- theme: {
137
- completeColor: t => `\x1b[32m${t}\x1b[39m`,
138
- incompleteColor: t => `\x1b[90m${t}\x1b[39m`,
139
- percentageColor: t => `\x1b[1m${t}\x1b[22m`,
140
- phaseColor: t => `\x1b[36m${t}\x1b[39m`,
141
- moduleColor: t => `\x1b[90m${t}\x1b[39m`
142
- }
143
- })
144
- ```
145
-
146
- ---
147
-
148
- ### bundleAnalyzer
149
-
150
- Automatically analyze build artifacts in the output directory after Vite build, generating size statistics, module rankings, file type distribution, and other key metrics, with JSON report and HTML visualization support.
151
-
152
- **Core Features:**
153
-
154
- - Scan build output directory, analyze chunks, modules, and asset files
155
- - Calculate original size and gzip compressed size
156
- - File type distribution statistics by extension
157
- - Top N largest modules ranking
158
- - Size threshold alerts (2x threshold marked as critical)
159
- - Compare with previous build results and generate diff report
160
- - HTML reports support treemap / sunburst / list visualization charts
161
-
162
- | Option | Type | Default | Description |
163
- | ------------------ | --------------------------------------- | ------------------- | --------------------------------------------------------- |
164
- | outputFormat | `'json'` \| `'html'` \| `'both'` | `'json'` | Report output format |
165
- | outputFile | `string` | `'bundle-analysis'` | Report output filename (without extension) |
166
- | openAnalyzer | `boolean` | `false` | Whether to auto-open browser after generating HTML report |
167
- | sizeThreshold | `number` | `100` | Size alert threshold (KB) |
168
- | topModules | `number` | `20` | Top N largest modules ranking count |
169
- | gzipSize | `boolean` | `true` | Whether to calculate gzip size |
170
- | excludeNodeModules | `boolean` | `false` | Whether to exclude node_modules modules |
171
- | excludePatterns | `string[]` | `[]` | File path patterns to exclude |
172
- | includeExtensions | `string[]` | `[]` | File extensions to include, empty means all |
173
- | compareWith | `string` \| `null` | `null` | Path to previous analysis report for comparison |
174
- | defaultChartType | `'treemap'` \| `'sunburst'` \| `'list'` | `'treemap'` | Default chart type in HTML report |
175
-
176
- ```typescript
177
- bundleAnalyzer()
178
- bundleAnalyzer({ outputFormat: 'both', openAnalyzer: true })
179
- bundleAnalyzer({ sizeThreshold: 200, topModules: 30, gzipSize: true })
180
- bundleAnalyzer({ compareWith: 'dist/bundle-analysis.json', defaultChartType: 'sunburst' })
181
- bundleAnalyzer({ excludeNodeModules: true, includeExtensions: ['.js', '.css'] })
182
- ```
183
-
184
- ---
185
-
186
- ### compressAssets
187
-
188
- Automatically compress files in the output directory after Vite build, supporting both gzip and brotli compression algorithms.
189
-
190
- | Option | Type | Default | Description |
191
- | ------------------ | ---------------------------------- | ----------------------------------------------------------- | -------------------------------------------------- |
192
- | algorithm | `'gzip'` \| `'brotli'` \| `'both'` | `'gzip'` | Compression algorithm |
193
- | threshold | `number` | `1024` | Minimum compression threshold (bytes) |
194
- | deleteOriginalFile | `boolean` | `false` | Whether to delete original files after compression |
195
- | includeExtensions | `string[]` | `['.js', '.css', '.html', '.svg', '.json', '.xml', '.txt']` | File extensions to compress |
196
- | excludeExtensions | `string[]` | `[]` | File extensions to exclude |
197
- | excludePaths | `string[]` | `[]` | Path prefixes to exclude |
198
- | compressionLevel | `number` | `9` | Gzip compression level (1-9) |
199
- | brotliQuality | `number` | `11` | Brotli compression quality (1-11) |
200
- | reportOutput | `string` \| `false` | `'compress-report.json'` | Compression report output path, false to skip |
201
- | parallelLimit | `number` | `10` | Maximum concurrent file compression count |
202
-
203
- ```typescript
204
- compressAssets()
205
- compressAssets({ algorithm: 'brotli' })
206
- compressAssets({ algorithm: 'both', threshold: 2048, compressionLevel: 9, brotliQuality: 11 })
207
- compressAssets({ deleteOriginalFile: true, reportOutput: 'compress-report.json' })
208
- compressAssets({ includeExtensions: ['.js', '.css'], excludePaths: ['assets/images'], parallelLimit: 5 })
209
- ```
210
-
211
- ---
212
-
213
- ### copyFile
214
-
215
- Copy files or directories to specified locations after Vite build is completed, with `enforce: 'post'`.
216
-
217
- | Option | Type | Default | Description |
218
- | ----------- | --------- | ------- | ------------------------------------------ |
219
- | sourceDir | `string` | - | Source directory path (required) |
220
- | targetDir | `string` | - | Target directory path (required) |
221
- | overwrite | `boolean` | `true` | Whether to overwrite existing files |
222
- | recursive | `boolean` | `true` | Whether to recursively copy subdirectories |
223
- | incremental | `boolean` | `true` | Whether to enable incremental copying |
224
-
225
- ```typescript
226
- copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' })
227
- copyFile({ sourceDir: 'src/static', targetDir: 'dist/static', overwrite: false, incremental: false })
228
- ```
229
-
230
- ---
231
-
232
- ### generateRouter
233
-
234
- Automatically generate router configuration files based on uni-app project's `pages.json`.
235
-
236
- | Option | Type | Default | Description |
237
- | -------------------- | --------------------------------------------------------- | ------------------------ | ------------------------------------------------ |
238
- | pagesJsonPath | `string` | `'src/pages.json'` | Path to pages.json file |
239
- | outputPath | `string` | `'src/router.config.ts'` | Output file path |
240
- | outputFormat | `'ts'` \| `'js'` | `'ts'` | Output file format |
241
- | nameStrategy | `'path'` \| `'camelCase'` \| `'pascalCase'` \| `'custom'` | `'camelCase'` | Route name strategy |
242
- | customNameGenerator | `(path: string) => string` | - | Custom route name generator function |
243
- | includeSubPackages | `boolean` | `true` | Whether to include sub-package routes |
244
- | watch | `boolean` | `true` | Whether to watch changes and auto-regenerate |
245
- | metaMapping | `Record<string, string>` | - | Mapping from page style fields to meta |
246
- | exportTypes | `boolean` | `true` | Whether to export type definitions |
247
- | preserveRouteChanges | `boolean` | `true` | Whether to preserve user modifications to routes |
248
-
249
- > Default `metaMapping` is `{ navigationBarTitleText: 'title', requireAuth: 'requireAuth' }`. When `nameStrategy` is `'custom'`, `customNameGenerator` must be provided.
250
-
251
- ```typescript
252
- generateRouter()
253
- generateRouter({ pagesJsonPath: 'pages.json' })
254
- generateRouter({ outputFormat: 'js', outputPath: 'src/router.config.js' })
255
- generateRouter({ nameStrategy: 'pascalCase' })
256
- generateRouter({ nameStrategy: 'custom', customNameGenerator: path => `route_${path.replace(/\//g, '_')}` })
257
- generateRouter({ metaMapping: { navigationBarTitleText: 'title', requireAuth: 'requireAuth', customField: 'custom' } })
258
- ```
259
-
260
- ---
261
-
262
- ### generateVersion
263
-
264
- Automatically generate version numbers during the Vite build process.
265
-
266
- | Option | Type | Default | Description |
267
- | ------------ | --------------------------------------------------------------------------------- | ------------------- | -------------------------------- |
268
- | format | `'timestamp'` \| `'date'` \| `'datetime'` \| `'semver'` \| `'hash'` \| `'custom'` | `'timestamp'` | Version number format |
269
- | customFormat | `string` | - | Custom format template |
270
- | semverBase | `string` | `'1.0.0'` | Semantic version base value |
271
- | outputType | `'file'` \| `'define'` \| `'both'` | `'file'` | Output type |
272
- | outputFile | `string` | `'version.json'` | Output file path |
273
- | defineName | `string` | `'__APP_VERSION__'` | Injected global variable name |
274
- | hashLength | `number` | `8` | Hash length (1-32) |
275
- | prefix | `string` | - | Version number prefix |
276
- | suffix | `string` | - | Version number suffix |
277
- | extra | `Record<string, unknown>` | - | Additional info (JSON file only) |
278
-
279
- **customFormat placeholders:**
280
-
281
- | Placeholder | Description | Example |
282
- | ------------- | ----------------------------------- | --------------- |
283
- | `{YYYY}` | Four-digit year | `2026` |
284
- | `{YY}` | Two-digit year | `26` |
285
- | `{MM}` | Two-digit month | `05` |
286
- | `{DD}` | Two-digit day | `22` |
287
- | `{HH}` | Two-digit hour (24h) | `15` |
288
- | `{mm}` | Two-digit minute | `30` |
289
- | `{ss}` | Two-digit second | `00` |
290
- | `{SSS}` | Three-digit millisecond | `123` |
291
- | `{timestamp}` | Timestamp (milliseconds) | `1779464601000` |
292
- | `{hash}` | Random hash | `a1b2c3d4` |
293
- | `{major}` | Major version (requires semverBase) | `1` |
294
- | `{minor}` | Minor version (requires semverBase) | `0` |
295
- | `{patch}` | Patch version (requires semverBase) | `0` |
296
-
297
- > When `format` is `'custom'`, `customFormat` must be provided. When `outputType` is `'define'` or `'both'`, a `{defineName}_INFO` global variable is also injected, containing complete info such as version, build time,
298
- > and timestamp.
299
-
300
- ```typescript
301
- generateVersion()
302
- generateVersion({ format: 'date' })
303
- generateVersion({ format: 'semver', semverBase: '2.0.0', prefix: 'v' })
304
- generateVersion({ format: 'custom', customFormat: '{YYYY}.{MM}.{DD}-{hash}', hashLength: 6 })
305
- generateVersion({ outputType: 'define', defineName: '__VERSION__' })
306
- generateVersion({ outputType: 'both', outputFile: 'build-info.json', defineName: '__BUILD_VERSION__', extra: { environment: 'production' } })
307
- ```
308
-
309
- ---
310
-
311
- ### versionUpdateChecker
312
-
313
- Periodically check for version changes at runtime, prompting users to refresh when a new version is detected. Typically used with the `generateVersion` plugin.
314
-
315
- **How it works:**
316
-
317
- 1. `generateVersion` generates a version file (`version.json`) or injects a global variable at build time
318
- 2. `versionUpdateChecker` periodically requests the version file at runtime and compares it with the current version
319
- 3. When a version mismatch is detected, a prompt is shown to guide the user to refresh
320
-
321
- | Option | Type | Default | Description |
322
- | ----------------------- | ------------------------------------ | -------------------------------------------- | ------------------------------------------------------------ |
323
- | versionSource | `'define'` \| `'file'` \| `'auto'` | `'auto'` | Current version source |
324
- | defineName | `string` | `'__APP_VERSION__'` | Global variable name in define mode |
325
- | checkUrl | `string` | `'/version.json'` | URL path for version check file |
326
- | checkInterval | `number` | `300000` | Check interval (ms, default 5 minutes) |
327
- | checkOnVisibilityChange | `boolean` | `true` | Whether to check immediately on page visibility change |
328
- | enableInDev | `boolean` | `false` | Whether to enable in development mode |
329
- | promptStyle | `'modal'` \| `'banner'` \| `'toast'` | `'modal'` | Update prompt UI style |
330
- | promptMessage | `string` | `'A new version is available. Refresh now?'` | Prompt message text |
331
- | refreshButtonText | `string` | `'Refresh Now'` | Refresh button text |
332
- | dismissButtonText | `string` | `'Later'` | Dismiss button text |
333
- | customPromptTemplate | `string` | - | Custom HTML template for the prompt UI |
334
- | customStyle | `string` | - | Custom CSS style string |
335
- | onUpdateAvailable | `string` | - | Callback when new version is found (function body string) |
336
- | onRefresh | `string` | - | Callback when user chooses to refresh (function body string) |
337
- | onDismiss | `string` | - | Callback when user chooses to dismiss (function body string) |
338
-
339
- > `versionSource` explanation: `'define'` reads from global variable, `'file'` reads from version file, `'auto'` prefers define and falls back to file. Custom templates can use `{{message}}`, `{{currentVersion}}`,
340
- > `{{newVersion}}`, `{{refreshButton}}`, `{{dismissButton}}` placeholders. Callbacks are provided as function body strings, available variables: `currentVersion`, `newVersion`.
341
-
342
- ```typescript
343
- generateVersion({ outputType: 'both' })
344
- versionUpdateChecker()
345
- versionUpdateChecker({ versionSource: 'file' })
346
- versionUpdateChecker({ checkInterval: 60000, promptStyle: 'banner' })
347
- versionUpdateChecker({ promptStyle: 'toast' })
348
- versionUpdateChecker({ promptMessage: 'System updated, refresh to experience new features', refreshButtonText: 'Update', dismissButtonText: 'Cancel' })
349
- versionUpdateChecker({ onUpdateAvailable: 'console.log("New version:", newVersion); return true;', onRefresh: 'console.log("User chose refresh");', onDismiss: 'console.log("User chose dismiss");' })
350
- versionUpdateChecker({ enableInDev: true })
351
- ```
352
-
353
- ---
354
-
355
- ### htmlInject
356
-
357
- Inject custom content into HTML files, supporting multiple positions, selector targeting, conditional injection, template variable replacement, and security filtering.
358
-
359
- | Option | Type | Default | Description |
360
- | ------------ | ------------------------ | -------------- | ------------------------------------------- |
361
- | targetFile | `string` | `'index.html'` | Target HTML file path or filename |
362
- | rules | `InjectRule[]` | - | Injection rules list (required) |
363
- | security | `SecurityConfig` | - | Security filtering config |
364
- | templateVars | `Record<string, string>` | `{}` | Global template variable mapping |
365
- | logInjection | `boolean` | `true` | Whether to output injection logs to console |
366
-
367
- **InjectRule**
368
-
369
- | Property | Type | Default | Description |
370
- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------------------------------------------------- |
371
- | id | `string` | - | Unique rule identifier |
372
- | content | `string` | - | Content to inject |
373
- | position | `'head-start'` \| `'head-end'` \| `'body-start'` \| `'body-end'` \| `'before-selector'` \| `'after-selector'` \| `'replace-selector'` | - | Injection position |
374
- | selector | `string` | - | Selector string (required for selector-related positions) |
375
- | selectorMatch | `'string'` \| `'regex'` | `'string'` | Selector match mode |
376
- | priority | `number` | `100` | Rule priority, lower values execute first |
377
- | condition | `InjectCondition` | - | Injection condition |
378
- | templateVars | `Record<string, string>` | - | Rule-level template variables (override global) |
379
- | allowScriptInjection | `boolean` | `false` | Whether to allow injecting scripts and dangerous content |
380
-
381
- **InjectCondition**
382
-
383
- | Property | Type | Default | Description |
384
- | -------- | ------------------------------------------ | ------- | -------------------------------------- |
385
- | type | `'env'` \| `'file-contains'` \| `'custom'` | - | Condition type |
386
- | value | `string` \| `(...args: any[]) => boolean` | - | Condition value |
387
- | negate | `boolean` | `false` | Whether to negate the condition result |
388
-
389
- **SecurityConfig**
390
-
391
- | Property | Type | Default | Description |
392
- | ------------------------ | ---------- | ------- | ----------------------------------------------------- |
393
- | blockDangerousTags | `boolean` | `true` | Whether to block dangerous tags (script, etc.) |
394
- | blockDangerousAttributes | `boolean` | `true` | Whether to block dangerous attributes (onclick, etc.) |
395
- | allowedTags | `string[]` | - | Whitelist of allowed tags |
396
- | blockedTags | `string[]` | - | Custom blocked tags list |
397
- | blockedAttributes | `string[]` | - | Custom blocked attributes list |
398
-
399
- ```typescript
400
- htmlInject({
401
- rules: [
402
- { id: 'meta-description', content: '<meta name="description" content="My App">', position: 'head-end' },
403
- { id: 'analytics', content: '<script src="https://analytics.example.com/track.js"></script>', position: 'body-end', allowScriptInjection: true },
404
- { id: 'env-var', content: '<script>window.__ENV__ = "{{env}}"</script>', position: 'head-end', templateVars: { env: 'production' }, allowScriptInjection: true },
405
- { id: 'before-app', content: '<div>Before App</div>', position: 'before-selector', selector: '<div id="app">' },
406
- { id: 'prod-only', content: '<meta name="robots" content="noindex">', position: 'head-end', condition: { type: 'env', value: 'PRODUCTION' } }
407
- ]
408
- })
409
- ```
410
-
411
- ---
412
-
413
- ### faviconManager
414
-
415
- Manage website favicon links injection into HTML files, supports icon file copying, supports string shorthand config.
416
-
417
- | Option | Type | Default | Description |
418
- | ----------- | ------------- | ------- | ------------------------------------------------------ |
419
- | base | `string` | `'/'` | Base path for icon files |
420
- | url | `string` | - | Complete icon URL (overrides base + favicon.ico) |
421
- | link | `string` | - | Custom complete link tag HTML (highest priority) |
422
- | icons | `Icon[]` | - | Custom icon array, supports multiple formats and sizes |
423
- | copyOptions | `CopyOptions` | - | Icon file copying config |
424
-
425
- **Icon**
426
-
427
- | Property | Type | Description |
428
- | -------- | -------- | ------------------ |
429
- | rel | `string` | Icon relation type |
430
- | href | `string` | Icon URL |
431
- | sizes | `string` | Icon sizes |
432
- | type | `string` | Icon MIME type |
433
-
434
- **CopyOptions**
435
-
436
- | Property | Type | Default | Description |
437
- | --------- | --------- | ------- | ----------------------------------- |
438
- | sourceDir | `string` | - | Icon source directory (required) |
439
- | targetDir | `string` | - | Icon target directory (required) |
440
- | overwrite | `boolean` | `true` | Whether to overwrite existing files |
441
- | recursive | `boolean` | `true` | Whether to copy recursively |
442
-
443
- ```typescript
444
- faviconManager('/assets')
445
- faviconManager({ base: '/assets', url: '/assets/favicon.ico' })
446
- faviconManager({
447
- base: '/assets',
448
- icons: [
449
- { rel: 'icon', href: '/favicon.svg', type: 'image/svg+xml' },
450
- { rel: 'icon', href: '/favicon-32x32.png', sizes: '32x32', type: 'image/png' }
451
- ]
452
- })
453
- faviconManager({
454
- base: '/assets',
455
- copyOptions: { sourceDir: 'src/assets/icons', targetDir: 'dist/assets/icons' }
456
- })
457
- ```
458
-
459
- ---
460
-
461
- ### loadingManager
462
-
463
- Global Loading state management with request interception, debounce, transition animations, and white-screen Loading.
464
-
465
- | Option | Type | Default | Description |
466
- | -------------- | ------------------ | ----------------------- | ------------------------------------------------------------- |
467
- | position | `LoadingPosition` | `'center'` | Loading display position |
468
- | defaultText | `string` | `'Loading...'` | Default display text |
469
- | spinnerType | `SpinnerType` | `'spinner'` | Spinner icon type |
470
- | style | `LoadingStyle` | - | Custom style config |
471
- | transition | `TransitionConfig` | - | Transition animation config |
472
- | minDisplayTime | `MinDisplayTime` | - | Minimum display time config |
473
- | delayShow | `DelayShow` | - | Delay show config |
474
- | debounceHide | `DebounceHide` | - | Debounce hide config |
475
- | autoBind | `AutoBindMode` | `'none'` | Auto-bind request interception mode |
476
- | requestFilter | `RequestFilter` | - | Request filter config |
477
- | globalName | `string` | `'__LOADING_MANAGER__'` | Injected global variable name |
478
- | customTemplate | `string` | - | Custom Loading HTML template |
479
- | defaultVisible | `boolean` | `false` | Loading DOM initial visibility (white-screen Loading) |
480
- | autoHideOn | `AutoHideOn` | `'DOMContentLoaded'` | Auto-hide timing (only effective when defaultVisible is true) |
481
- | callbacks | `LoadingCallbacks` | - | Lifecycle callbacks |
482
-
483
- **LoadingPosition**: `'center'` | `'top'` | `'bottom'`
484
-
485
- **SpinnerType**: `'spinner'` | `'dots'` | `'pulse'` | `'bar'`
486
-
487
- **AutoBindMode**: `'fetch'` | `'xhr'` | `'all'` | `'none'`
488
-
489
- **AutoHideOn**: `'DOMContentLoaded'` | `'load'` | `'manual'`
490
-
491
- **LoadingStyle**
492
-
493
- | Property | Type | Default | Description |
494
- | ------------------ | --------- | ------------------------- | ---------------------------------------- |
495
- | overlayColor | `string` | `'rgba(255,255,255,0.7)'` | Overlay background color |
496
- | spinnerColor | `string` | `'#4361ee'` | Loading icon color |
497
- | spinnerSize | `string` | `'40px'` | Loading icon size |
498
- | textColor | `string` | `'#333'` | Text color |
499
- | textSize | `string` | `'14px'` | Text size |
500
- | customClass | `string` | - | Custom CSS class name |
501
- | customStyle | `string` | - | Custom inline style string |
502
- | zIndex | `number` | `9999` | Overlay z-index |
503
- | pointerEvents | `boolean` | `true` | Whether to enable overlay pointer events |
504
- | backdropBlur | `boolean` | `false` | Whether to enable backdrop blur |
505
- | backdropBlurAmount | `number` | `4` | Backdrop blur amount (px) |
506
-
507
- **TransitionConfig**
508
-
509
- | Property | Type | Default | Description |
510
- | -------- | --------- | ------------ | ------------------------------ |
511
- | enabled | `boolean` | `true` | Whether to enable transition |
512
- | duration | `number` | `200` | Transition duration (ms) |
513
- | easing | `string` | `'ease-out'` | CSS transition easing function |
514
-
515
- **MinDisplayTime**
516
-
517
- | Property | Type | Default | Description |
518
- | -------- | --------- | ------- | -------------------------------------- |
519
- | enabled | `boolean` | `true` | Whether to enable minimum display time |
520
- | duration | `number` | `300` | Minimum display time (ms) |
521
-
522
- **DelayShow**
523
-
524
- | Property | Type | Default | Description |
525
- | -------- | --------- | ------- | --------------------------------------------------------------- |
526
- | enabled | `boolean` | `true` | Whether to enable delay show |
527
- | duration | `number` | `200` | Delay time (ms), requests completed within this time won't show |
528
-
529
- **DebounceHide**
530
-
531
- | Property | Type | Default | Description |
532
- | -------- | --------- | ------- | ------------------------------- |
533
- | enabled | `boolean` | `false` | Whether to enable debounce hide |
534
- | duration | `number` | `100` | Debounce wait time (ms) |
535
-
536
- **RequestFilter**
537
-
538
- | Property | Type | Description |
539
- | ------------------ | ---------- | ------------------------------ |
540
- | excludeUrls | `RegExp[]` | URL regex patterns to exclude |
541
- | includeUrls | `RegExp[]` | URL regex patterns to include |
542
- | excludeMethods | `string[]` | HTTP methods to exclude |
543
- | excludeUrlPrefixes | `string[]` | URL string prefixes to exclude |
544
-
545
- **LoadingCallbacks**
546
-
547
- | Property | Type | Description |
548
- | ------------ | -------- | -------------------------------------------------------- |
549
- | onBeforeShow | `string` | Before show callback (`return false` to prevent showing) |
550
- | onShow | `string` | After show callback |
551
- | onBeforeHide | `string` | Before hide callback (`return false` to prevent hiding) |
552
- | onHide | `string` | After hide callback |
553
- | onDestroy | `string` | On destroy callback |
554
-
555
- > Callbacks are provided as function body strings because they need to be injected into client-side code. `customTemplate` must contain an element with the `data-loading-text` attribute for text display.
556
-
557
- **Runtime API:**
558
-
559
- ```typescript
560
- window.__LOADING_MANAGER__.show('Loading...')
561
- window.__LOADING_MANAGER__.hide()
562
- window.__LOADING_MANAGER__.forceHide()
563
- window.__LOADING_MANAGER__.toggle('Loading...')
564
- window.__LOADING_MANAGER__.updateText('Processing...')
565
- window.__LOADING_MANAGER__.isVisible()
566
- window.__LOADING_MANAGER__.getPendingCount()
567
- window.__LOADING_MANAGER__.enablePointerEvents()
568
- window.__LOADING_MANAGER__.disablePointerEvents()
569
- window.__LOADING_MANAGER__.destroy()
570
- ```
571
-
572
- ```typescript
573
- loadingManager()
574
- loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
575
- loadingManager({ position: 'top', defaultText: 'Please wait...', spinnerType: 'dots' })
576
- loadingManager({ autoBind: 'fetch', requestFilter: { excludeUrls: [/\/api\/health/] } })
577
- loadingManager({
578
- style: { overlayColor: 'rgba(0,0,0,0.5)', spinnerColor: '#ff6b6b', backdropBlur: true, backdropBlurAmount: 6 }
579
- })
580
- loadingManager({ transition: { enabled: true, duration: 300, easing: 'cubic-bezier(0.4,0,0.2,1)' } })
581
- loadingManager({ debounceHide: { enabled: true, duration: 100 } })
582
- loadingManager({ callbacks: { onShow: 'console.log("shown")', onBeforeShow: 'return true' } })
583
- loadingManager({ customTemplate: '<div class="my-loader"><span data-loading-text></span></div>' })
584
- loadingManager({ defaultVisible: true, autoHideOn: 'manual' })
585
- ```
586
-
587
- ---
66
+ | Plugin | Description |
67
+ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
68
+ | [autoImport](https://mengxi-studio.github.io/vite-plugin/en/plugins/auto-import.html) | Auto-inject import statements with preset mappings, directory scanning, and Vue template auto-import |
69
+ | [buildProgress](https://mengxi-studio.github.io/vite-plugin/en/plugins/build-progress.html) | Real-time terminal build progress bar, supports bar / spinner / minimal |
70
+ | [bundleAnalyzer](https://mengxi-studio.github.io/vite-plugin/en/plugins/bundle-analyzer.html) | Bundle volume analysis with JSON/HTML reports, gzip calculation, threshold alerts, and build diff |
71
+ | [compressAssets](https://mengxi-studio.github.io/vite-plugin/en/plugins/compress-assets.html) | Asset compression with gzip / brotli / both, concurrent compression and statistics report |
72
+ | [copyFile](https://mengxi-studio.github.io/vite-plugin/en/plugins/copy-file.html) | Copy files or directories after build, supports incremental copying |
73
+ | [envGuard](https://mengxi-studio.github.io/vite-plugin/en/plugins/) | Environment variable validation with type checking, range validation, custom rules and runtime guard |
74
+ | [faviconManager](https://mengxi-studio.github.io/vite-plugin/en/plugins/favicon-manager.html) | Manage website favicon link injection and file copying, supports string shorthand config |
75
+ | [generateRouter](https://mengxi-studio.github.io/vite-plugin/en/plugins/generate-router.html) | Auto-generate route config from pages.json (uni-app) |
76
+ | [generateVersion](https://mengxi-studio.github.io/vite-plugin/en/plugins/generate-version.html) | Auto-generate version numbers with file output and global variable injection |
77
+ | [htmlInject](https://mengxi-studio.github.io/vite-plugin/en/plugins/html-inject.html) | HTML content injection with multiple positions, selector targeting, conditional injection, template variables, and security filtering |
78
+ | [loadingManager](https://mengxi-studio.github.io/vite-plugin/en/plugins/loading-manager.html) | Global Loading state management with request interception, debounce, transition animations, and white-screen Loading |
79
+ | [versionUpdateChecker](https://mengxi-studio.github.io/vite-plugin/en/plugins/version-update-checker.html) | Runtime version update checking with multiple prompt styles and custom callbacks |
588
80
 
589
81
  ## Plugin Development Framework
590
82
 
591
- This package not only provides built-in plugins but also exports a complete plugin development framework to help quickly build custom Vite plugins that follow conventions.
592
-
593
- ### BasePlugin
594
-
595
- The base class for all built-in plugins, providing core capabilities such as configuration management, logging, error handling, and lifecycle management.
83
+ This package exports a complete plugin development framework to help quickly build custom Vite plugins that follow conventions.
596
84
 
597
85
  ```typescript
598
86
  import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
@@ -630,240 +118,33 @@ class MyPlugin extends BasePlugin<MyPluginOptions> {
630
118
  export const myPlugin = createPluginFactory(MyPlugin)
631
119
  ```
632
120
 
633
- **BasePlugin Core Methods:**
634
-
635
- | Method | Description |
636
- | ------------------- | -------------------------------------------------------------- |
637
- | `getDefaultOptions` | Returns plugin default config, can be overridden by subclasses |
638
- | `validateOptions` | Validates user config, can be overridden by subclasses |
639
- | `getPluginName` | Returns plugin name (abstract method, must be implemented) |
640
- | `getEnforce` | Returns plugin execution timing (pre / post / undefined) |
641
- | `addPluginHooks` | Registers Vite hooks (abstract method, must be implemented) |
642
- | `onConfigResolved` | Config resolution complete callback |
643
- | `destroy` | Plugin destroy callback |
644
- | `safeExecute` | Safely execute async function with automatic error handling |
645
- | `safeExecuteSync` | Safely execute sync function with automatic error handling |
646
- | `handleError` | Handle errors based on errorStrategy |
647
- | `toPlugin` | Convert to Vite plugin object |
648
-
649
- **BasePluginOptions Base Config:**
650
-
651
- | Option | Type | Default | Description |
652
- | ------------- | ---------------------------------- | --------- | ----------------------- |
653
- | enabled | `boolean` | `true` | Whether to enable |
654
- | verbose | `boolean` | `true` | Whether to log |
655
- | errorStrategy | `'throw'` \| `'log'` \| `'ignore'` | `'throw'` | Error handling strategy |
656
-
657
- ### createPluginFactory
658
-
659
- Creates a plugin factory function that converts a BasePlugin subclass into a directly usable Vite plugin function.
660
-
661
- ```typescript
662
- import { createPluginFactory } from '@meng-xi/vite-plugin'
663
-
664
- const myPlugin = createPluginFactory(MyPlugin)
665
-
666
- // Supports options normalizer (e.g. string shorthand config)
667
- const myPluginWithNormalizer = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { prefix: opt } : opt))
668
- ```
669
-
670
- ### Logger
671
-
672
- Global singleton log manager, providing independent log proxies for each plugin.
673
-
674
- ```typescript
675
- import { Logger } from '@meng-xi/vite-plugin/logger'
676
-
677
- const logger = Logger.create({ name: 'my-plugin', enabled: true })
678
- logger.info('Info log')
679
- logger.success('Success log')
680
- logger.warn('Warning log')
681
- logger.error('Error log')
682
- ```
121
+ **Core API:**
683
122
 
684
- ### Validator
685
-
686
- Chain-style configuration validator for validating plugin configuration parameters.
687
-
688
- ```typescript
689
- import { Validator } from '@meng-xi/vite-plugin/common/validation'
690
-
691
- const validator = new Validator(myOptions)
692
- validator.field('port').number().minValue(1).maxValue(65535).field('host').string().notEmpty().field('mode').enum(['development', 'production']).validate()
693
- ```
694
-
695
- ---
123
+ | API | Description |
124
+ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
125
+ | [`BasePlugin`](https://mengxi-studio.github.io/vite-plugin/en/factory/base-plugin.html) | Plugin base class providing config management, logging, error handling and lifecycle |
126
+ | [`createPluginFactory`](https://mengxi-studio.github.io/vite-plugin/en/factory/create-plugin-factory.html) | Converts a BasePlugin subclass into a Vite plugin function |
127
+ | [`Logger`](https://mengxi-studio.github.io/vite-plugin/en/logger/) | Global singleton log manager with independent log proxies per plugin |
128
+ | [`Validator`](https://mengxi-studio.github.io/vite-plugin/en/factory/) | Chain-style configuration validator for plugin config parameters |
696
129
 
697
130
  ## Common Utility Modules
698
131
 
699
132
  Built-in general-purpose utility function library, organized by functional modules, supporting on-demand sub-path imports.
700
133
 
701
- ### Import Methods
702
-
703
134
  ```typescript
704
- // Import all utilities
705
- import { formatFileSize, scanDirectory } from '@meng-xi/vite-plugin/common'
706
-
707
- // Import by module
708
135
  import { formatFileSize } from '@meng-xi/vite-plugin/common/format'
709
- import { scanDirectory, writeJsonReport } from '@meng-xi/vite-plugin/common/fs'
710
- import { calculateGzipSize } from '@meng-xi/vite-plugin/common/compress'
711
- import { isNodeModule } from '@meng-xi/vite-plugin/common/path'
136
+ import { scanDirectory } from '@meng-xi/vite-plugin/common/fs'
137
+ import { injectBeforeTag } from '@meng-xi/vite-plugin/common/html'
712
138
  ```
713
139
 
714
- ### Module List
715
-
716
- | Sub-path | Description |
717
- | ---------------------------------------- | ----------------------- |
718
- | `@meng-xi/vite-plugin/common/compress` | Compression utilities |
719
- | `@meng-xi/vite-plugin/common/format` | Formatting utilities |
720
- | `@meng-xi/vite-plugin/common/fs` | File system utilities |
721
- | `@meng-xi/vite-plugin/common/html` | HTML injection utils |
722
- | `@meng-xi/vite-plugin/common/object` | Object operation utils |
723
- | `@meng-xi/vite-plugin/common/path` | Path handling utils |
724
- | `@meng-xi/vite-plugin/common/script` | Script generation utils |
725
- | `@meng-xi/vite-plugin/common/validation` | Validation utilities |
726
-
727
- ### compress — Compression
728
-
729
- | Function | Description |
730
- | ------------------- | ---------------------------------------------------- |
731
- | `calculateGzipSize` | Calculate gzip compressed size of given data (bytes) |
732
-
733
- ```typescript
734
- import { calculateGzipSize } from '@meng-xi/vite-plugin/common/compress'
735
-
736
- const size = await calculateGzipSize(Buffer.from('hello world'))
737
- ```
738
-
739
- ### format — Formatting
740
-
741
- | Function | Description |
742
- | --------------------- | -------------------------------------------------- |
743
- | `formatFileSize` | Format bytes to human-readable file size string |
744
- | `getExtension` | Get file extension (lowercase) |
745
- | `formatDate` | Format date |
746
- | `parseTemplate` | Parse template string, replace placeholders |
747
- | `toCamelCase` | Convert string to camelCase |
748
- | `toPascalCase` | Convert string to PascalCase |
749
- | `padNumber` | Pad number with leading zeros |
750
- | `generateRandomHash` | Generate random hash string |
751
- | `getDateFormatParams` | Get date formatting parameters |
752
- | `stripJsonComments` | Remove comments from JSON string |
753
- | `escapeHtmlAttr` | Escape special characters in HTML attribute values |
754
-
755
- ```typescript
756
- import { formatFileSize, formatDate, toCamelCase } from '@meng-xi/vite-plugin/common/format'
757
-
758
- formatFileSize(2461726) // '2.35MB'
759
- formatDate(new Date(), '{YYYY}-{MM}-{DD}') // '2026-05-31'
760
- toCamelCase('pages/user/profile') // 'pagesUserProfile'
761
- ```
762
-
763
- ### fs — File System
764
-
765
- | Function | Description |
766
- | -------------------- | --------------------------------------------- |
767
- | `scanDirectory` | Recursively scan directory, collect file info |
768
- | `writeJsonReport` | Write data to JSON file |
769
- | `writeFileContent` | Write file content |
770
- | `readFileContent` | Read file content |
771
- | `fileExists` | Check if file exists |
772
- | `checkSourceExists` | Check if source file exists |
773
- | `ensureTargetDir` | Create target directory |
774
- | `copySourceToTarget` | Execute file copy operation |
775
- | `runWithConcurrency` | Batch execution with concurrency limit |
776
-
777
- ```typescript
778
- import { scanDirectory, writeJsonReport } from '@meng-xi/vite-plugin/common/fs'
779
-
780
- const files = await scanDirectory('dist', {
781
- includeExtensions: ['.js', '.css'],
782
- excludePatterns: ['node_modules'],
783
- filter: (filePath, ext, size) => size > 1024
784
- })
785
-
786
- await writeJsonReport('dist/report.json', { timestamp: Date.now(), files })
787
- ```
788
-
789
- ### html — HTML Injection
790
-
791
- | Function | Description |
792
- | ----------------------------- | ---------------------------------------- |
793
- | `injectBeforeTag` | Inject code before specified closing tag |
794
- | `injectHtmlByPriority` | Inject code into HTML by priority |
795
- | `injectBeforeTagWithFallback` | Inject code with fallback strategy |
796
- | `injectHeadAndBody` | Dual-zone HTML injection (head + body) |
797
-
798
- ```typescript
799
- import { injectBeforeTag, injectHeadAndBody } from '@meng-xi/vite-plugin/common/html'
800
-
801
- const result = injectBeforeTag(html, '</head>', '<style>body{margin:0}</style>')
802
- const dual = injectHeadAndBody(html, '<style>...</style>', '<script>...</script>')
803
- ```
804
-
805
- ### object — Object Operations
806
-
807
- | Function | Description |
808
- | ----------- | ------------------ |
809
- | `deepMerge` | Deep merge objects |
810
-
811
- ```typescript
812
- import { deepMerge } from '@meng-xi/vite-plugin/common/object'
813
-
814
- deepMerge({ a: { b: 1 } }, { a: { c: 2 } }) // { a: { b: 1, c: 2 } }
815
- ```
816
-
817
- ### path — Path Handling
818
-
819
- | Function | Description |
820
- | -------------- | --------------------------------------- |
821
- | `isNodeModule` | Check if module ID is from node_modules |
822
-
823
- ```typescript
824
- import { isNodeModule } from '@meng-xi/vite-plugin/common/path'
825
-
826
- isNodeModule('node_modules/lodash/index.js') // true
827
- isNodeModule('src/utils/helper.ts') // false
828
- ```
829
-
830
- ### script — Script Generation
831
-
832
- | Function | Description |
833
- | ------------------------ | -------------------------------------------------------------- |
834
- | `makeCallback` | Wrap callback function body string as safe function expression |
835
- | `containsScriptTag` | Detect if string contains `<script>` tag |
836
- | `validateIdentifierName` | Validate if string is a valid JS identifier |
837
-
838
- ```typescript
839
- import { makeCallback, validateIdentifierName } from '@meng-xi/vite-plugin/common/script'
840
-
841
- makeCallback('console.log("done")')
842
- // 'function() { try { console.log("done") } catch(e) { console.error("[callback] error:", e); } }'
843
-
844
- validateIdentifierName('__APP_VERSION__') // passes
845
- ```
846
-
847
- ### validation — Validation
848
-
849
- | Function | Description |
850
- | ---------------------------- | ----------------------------------- |
851
- | `Validator` | Chain-style configuration validator |
852
- | `validateGlobalName` | Validate global variable name |
853
- | `validateNoScriptInTemplate` | Validate no script tag in template |
854
- | `validateCallbackFields` | Validate callback function fields |
855
- | `validateNonNegativeNumber` | Validate non-negative number |
856
- | `validateNestedDuration` | Validate nested duration config |
857
- | `validateEnumValue` | Validate enum value |
858
-
859
- ```typescript
860
- import { Validator } from '@meng-xi/vite-plugin/common/validation'
861
-
862
- const validator = new Validator(options)
863
- validator.field('port').number().minValue(1).maxValue(65535).validate()
864
- ```
865
-
866
- ---
140
+ | Sub-path | Description |
141
+ | -------------------------------------------------------------------------------------------- | ----------------------- |
142
+ | [`common/format`](https://mengxi-studio.github.io/vite-plugin/en/common/format.html) | Formatting utilities |
143
+ | [`common/fs`](https://mengxi-studio.github.io/vite-plugin/en/common/fs.html) | File system utilities |
144
+ | [`common/html`](https://mengxi-studio.github.io/vite-plugin/en/common/html.html) | HTML injection utils |
145
+ | [`common/script`](https://mengxi-studio.github.io/vite-plugin/en/common/script.html) | Script generation utils |
146
+ | [`common/ui`](https://mengxi-studio.github.io/vite-plugin/en/common/ui.html) | Terminal UI utils |
147
+ | [`common/validation`](https://mengxi-studio.github.io/vite-plugin/en/common/validation.html) | Validation utilities |
867
148
 
868
149
  ## Sub-path Exports
869
150
 
@@ -874,18 +155,13 @@ validator.field('port').number().minValue(1).maxValue(65535).validate()
874
155
  | `@meng-xi/vite-plugin/logger` | Log manager |
875
156
  | `@meng-xi/vite-plugin/plugins` | All plugins |
876
157
  | `@meng-xi/vite-plugin/common` | All utility functions |
877
- | `@meng-xi/vite-plugin/common/compress` | Compression utilities |
878
- | `@meng-xi/vite-plugin/common/format` | Formatting utilities |
879
- | `@meng-xi/vite-plugin/common/fs` | File system utilities |
880
- | `@meng-xi/vite-plugin/common/html` | HTML injection utilities |
881
- | `@meng-xi/vite-plugin/common/object` | Object operation utilities |
882
- | `@meng-xi/vite-plugin/common/path` | Path handling utilities |
883
- | `@meng-xi/vite-plugin/common/script` | Script generation utilities |
884
- | `@meng-xi/vite-plugin/common/validation` | Validation utilities |
158
+ | `@meng-xi/vite-plugin/common/*` | Utility sub-modules |
159
+ | `@meng-xi/vite-plugin/plugins/auto-import` | autoImport plugin |
885
160
  | `@meng-xi/vite-plugin/plugins/build-progress` | buildProgress plugin |
886
161
  | `@meng-xi/vite-plugin/plugins/bundle-analyzer` | bundleAnalyzer plugin |
887
162
  | `@meng-xi/vite-plugin/plugins/compress-assets` | compressAssets plugin |
888
163
  | `@meng-xi/vite-plugin/plugins/copy-file` | copyFile plugin |
164
+ | `@meng-xi/vite-plugin/plugins/env-guard` | envGuard plugin |
889
165
  | `@meng-xi/vite-plugin/plugins/favicon-manager` | faviconManager plugin |
890
166
  | `@meng-xi/vite-plugin/plugins/generate-router` | generateRouter plugin |
891
167
  | `@meng-xi/vite-plugin/plugins/generate-version` | generateVersion plugin |
@@ -893,8 +169,6 @@ validator.field('port').number().minValue(1).maxValue(65535).validate()
893
169
  | `@meng-xi/vite-plugin/plugins/loading-manager` | loadingManager plugin |
894
170
  | `@meng-xi/vite-plugin/plugins/version-update-checker` | versionUpdateChecker plugin |
895
171
 
896
- ---
897
-
898
172
  ## License
899
173
 
900
174
  [MIT](LICENSE)