@meng-xi/vite-plugin 0.1.2 → 0.1.4

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 (106) hide show
  1. package/README-en.md +86 -510
  2. package/README.md +83 -506
  3. package/dist/common/compress/index.cjs +1 -0
  4. package/dist/common/compress/index.d.cts +23 -0
  5. package/dist/common/compress/index.d.mts +23 -0
  6. package/dist/common/compress/index.d.ts +23 -0
  7. package/dist/common/compress/index.mjs +1 -0
  8. package/dist/common/format/index.cjs +1 -1
  9. package/dist/common/format/index.d.cts +33 -1
  10. package/dist/common/format/index.d.mts +33 -1
  11. package/dist/common/format/index.d.ts +33 -1
  12. package/dist/common/format/index.mjs +1 -1
  13. package/dist/common/fs/index.cjs +1 -1
  14. package/dist/common/fs/index.d.cts +70 -2
  15. package/dist/common/fs/index.d.mts +70 -2
  16. package/dist/common/fs/index.d.ts +70 -2
  17. package/dist/common/fs/index.mjs +1 -1
  18. package/dist/common/html/index.cjs +2 -2
  19. package/dist/common/html/index.d.cts +268 -19
  20. package/dist/common/html/index.d.mts +268 -19
  21. package/dist/common/html/index.d.ts +268 -19
  22. package/dist/common/html/index.mjs +2 -2
  23. package/dist/common/index.cjs +1 -1
  24. package/dist/common/index.d.cts +8 -3
  25. package/dist/common/index.d.mts +8 -3
  26. package/dist/common/index.d.ts +8 -3
  27. package/dist/common/index.mjs +1 -1
  28. package/dist/common/path/index.cjs +1 -0
  29. package/dist/common/path/index.d.cts +22 -0
  30. package/dist/common/path/index.d.mts +22 -0
  31. package/dist/common/path/index.d.ts +22 -0
  32. package/dist/common/path/index.mjs +1 -0
  33. package/dist/common/ui/index.cjs +1 -0
  34. package/dist/common/ui/index.d.cts +132 -0
  35. package/dist/common/ui/index.d.mts +132 -0
  36. package/dist/common/ui/index.d.ts +132 -0
  37. package/dist/common/ui/index.mjs +1 -0
  38. package/dist/common/validation/index.cjs +1 -1
  39. package/dist/common/validation/index.d.cts +1 -0
  40. package/dist/common/validation/index.d.mts +1 -0
  41. package/dist/common/validation/index.d.ts +1 -0
  42. package/dist/common/validation/index.mjs +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.d.cts +11 -4
  45. package/dist/index.d.mts +11 -4
  46. package/dist/index.d.ts +11 -4
  47. package/dist/index.mjs +1 -1
  48. package/dist/plugins/buildProgress/index.cjs +2 -2
  49. package/dist/plugins/buildProgress/index.mjs +2 -2
  50. package/dist/plugins/bundleAnalyzer/index.cjs +235 -0
  51. package/dist/plugins/bundleAnalyzer/index.d.cts +215 -0
  52. package/dist/plugins/bundleAnalyzer/index.d.mts +215 -0
  53. package/dist/plugins/bundleAnalyzer/index.d.ts +215 -0
  54. package/dist/plugins/bundleAnalyzer/index.mjs +235 -0
  55. package/dist/plugins/compressAssets/index.cjs +1 -1
  56. package/dist/plugins/compressAssets/index.mjs +1 -1
  57. package/dist/plugins/copyFile/index.d.cts +20 -2
  58. package/dist/plugins/copyFile/index.d.mts +20 -2
  59. package/dist/plugins/copyFile/index.d.ts +20 -2
  60. package/dist/plugins/envGuard/index.cjs +67 -0
  61. package/dist/plugins/envGuard/index.d.cts +156 -0
  62. package/dist/plugins/envGuard/index.d.mts +156 -0
  63. package/dist/plugins/envGuard/index.d.ts +156 -0
  64. package/dist/plugins/envGuard/index.mjs +67 -0
  65. package/dist/plugins/faviconManager/index.cjs +1 -1
  66. package/dist/plugins/faviconManager/index.d.cts +43 -5
  67. package/dist/plugins/faviconManager/index.d.mts +43 -5
  68. package/dist/plugins/faviconManager/index.d.ts +43 -5
  69. package/dist/plugins/faviconManager/index.mjs +1 -1
  70. package/dist/plugins/generateRouter/index.cjs +4 -4
  71. package/dist/plugins/generateRouter/index.d.cts +61 -14
  72. package/dist/plugins/generateRouter/index.d.mts +61 -14
  73. package/dist/plugins/generateRouter/index.d.ts +61 -14
  74. package/dist/plugins/generateRouter/index.mjs +1 -1
  75. package/dist/plugins/generateVersion/index.cjs +1 -1
  76. package/dist/plugins/generateVersion/index.d.cts +12 -0
  77. package/dist/plugins/generateVersion/index.d.mts +12 -0
  78. package/dist/plugins/generateVersion/index.d.ts +12 -0
  79. package/dist/plugins/generateVersion/index.mjs +1 -1
  80. package/dist/plugins/htmlInject/index.cjs +1 -7
  81. package/dist/plugins/htmlInject/index.d.cts +49 -194
  82. package/dist/plugins/htmlInject/index.d.mts +49 -194
  83. package/dist/plugins/htmlInject/index.d.ts +49 -194
  84. package/dist/plugins/htmlInject/index.mjs +1 -7
  85. package/dist/plugins/index.cjs +1 -1
  86. package/dist/plugins/index.d.cts +5 -1
  87. package/dist/plugins/index.d.mts +5 -1
  88. package/dist/plugins/index.d.ts +5 -1
  89. package/dist/plugins/index.mjs +1 -1
  90. package/dist/plugins/loadingManager/index.cjs +2 -2
  91. package/dist/plugins/loadingManager/index.mjs +1 -1
  92. package/dist/plugins/versionUpdateChecker/index.cjs +2 -2
  93. package/dist/plugins/versionUpdateChecker/index.mjs +3 -3
  94. package/dist/shared/vite-plugin.BCuhU1au.mjs +7 -0
  95. package/dist/shared/vite-plugin.BrI73DHA.cjs +7 -0
  96. package/dist/shared/vite-plugin.CmtcnItg.d.cts +261 -0
  97. package/dist/shared/vite-plugin.CmtcnItg.d.mts +261 -0
  98. package/dist/shared/vite-plugin.CmtcnItg.d.ts +261 -0
  99. package/dist/shared/vite-plugin.DnFDPjNf.mjs +1 -0
  100. package/dist/shared/vite-plugin.Dumot0up.mjs +1 -0
  101. package/dist/shared/vite-plugin.FfJ-Wwfu.d.cts +143 -0
  102. package/dist/shared/vite-plugin.FfJ-Wwfu.d.mts +143 -0
  103. package/dist/shared/vite-plugin.FfJ-Wwfu.d.ts +143 -0
  104. package/dist/shared/vite-plugin.soT9a-KD.cjs +1 -0
  105. package/dist/shared/vite-plugin.vwox4bU0.cjs +1 -0
  106. package/package.json +26 -1
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,18 +15,14 @@
15
15
 
16
16
  ## Features
17
17
 
18
- - **Ready to Use** - Provides 9 practical plugins covering build progress display, build artifact compression, file copying, router generation, version management, version update checking, HTML injection, icon injection,
19
- and global Loading state management
20
- - **Plugin Development Framework** - Exports core components like BasePlugin, Logger, Validator for building custom Vite plugins
21
- - **Complete Lifecycle** - Supports initialization, config resolution, destroy lifecycle management with automatic hook composition
22
- - **Type Safe** - Complete TypeScript type definitions with configuration validators ensuring parameter correctness
23
- - **Flexible Configuration** - All plugins support detailed configuration to meet diverse scenario requirements
24
- - **Safe Execution** - Built-in error handling strategies (throw / log / ignore) for unified exception management
18
+ - **Ready to Use** - 11 practical plugins covering build progress, bundle analysis & compression, file copying, environment variable validation, route generation, version management, HTML injection, favicon management,
19
+ 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
25
23
  - **On-demand Import** - Supports sub-path exports to reduce bundle size
26
24
 
27
- ## Documentation
28
-
29
- 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/)**
30
26
 
31
27
  ## Installation
32
28
 
@@ -43,468 +39,76 @@ pnpm add @meng-xi/vite-plugin -D
43
39
 
44
40
  ## Quick Start
45
41
 
46
- ### Using Built-in Plugins
47
-
48
42
  ```typescript
49
43
  import { defineConfig } from 'vite'
50
- import { buildProgress, 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 } from '@meng-xi/vite-plugin'
51
45
 
52
46
  export default defineConfig({
53
47
  plugins: [
54
48
  buildProgress(),
49
+ bundleAnalyzer({ outputFormat: 'both' }),
55
50
  compressAssets({ algorithm: 'gzip' }),
56
51
  copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' }),
57
- generateRouter({ pagesJsonPath: 'src/pages.json', outputPath: 'src/router.config.ts' }),
52
+ envGuard({ rules: { VITE_API_URL: { type: 'string', required: true } } }),
53
+ generateRouter(),
58
54
  generateVersion({ format: 'datetime', outputType: 'both' }),
59
55
  versionUpdateChecker(),
60
- htmlInject({
61
- rules: [{ id: 'meta-description', content: '<meta name="description" content="My App">', position: 'head-end' }]
62
- }),
56
+ htmlInject({ rules: [{ id: 'meta', content: '<meta name="description" content="My App">', position: 'head-end' }] }),
63
57
  faviconManager('/assets'),
64
58
  loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
65
59
  ]
66
60
  })
67
61
  ```
68
62
 
69
- ### Accessing Plugin Instance
70
-
71
- All built-in plugins return an object with a `pluginInstance` property for accessing internal state:
72
-
73
- ```typescript
74
- import type { PluginWithInstance } from '@meng-xi/vite-plugin/factory'
75
- import type { GenerateRouterOptions } from '@meng-xi/vite-plugin'
76
-
77
- const routerPlugin = generateRouter({ watch: true }) as PluginWithInstance<GenerateRouterOptions>
78
- console.log(routerPlugin.pluginInstance?.options)
79
- ```
80
-
81
63
  ## Built-in Plugins
82
64
 
83
- | Plugin | Description |
84
- | -------------------- | ----------------------------------------------------------------------------------------------------------------- |
85
- | buildProgress | Real-time build progress bar in terminal, supports bar / spinner / minimal |
86
- | compressAssets | Compress build artifacts with gzip / brotli / both, concurrent compression and statistics report |
87
- | copyFile | Copy files or directories after build, supports incremental copying |
88
- | generateRouter | Auto-generate router config from pages.json (uni-app) |
89
- | generateVersion | Auto-generate version numbers, supports file output and global variable injection |
90
- | versionUpdateChecker | Runtime version update checking with multiple prompt styles and custom callbacks |
91
- | htmlInject | HTML content injection with multiple positions, conditional injection, template variables, and security filtering |
92
- | faviconManager | Manage website favicon links injection into HTML files, supports string shorthand config |
93
- | loadingManager | Global Loading state management with request interception and white-screen Loading |
94
-
95
- ---
96
-
97
- ### buildProgress
98
-
99
- Display real-time build progress bar in terminal during Vite build, supporting three display formats.
100
-
101
- **Progress calculation logic:**
102
-
103
- 1. config phase (5%) → resolve phase (10%) → transform phase (15%-85%, by module conversion ratio) → bundle phase (+10%) → write phase (+5%) → done (100%)
104
- 2. Non-TTY terminal environments (e.g. CI/CD) automatically degrade to log output mode
105
-
106
- | Option | Type | Default | Description |
107
- | --------------- | ------------------------------------- | ------- | ---------------------------------------------------- |
108
- | width | `number` | `30` | Progress bar width (characters) |
109
- | format | `'bar'` \| `'spinner'` \| `'minimal'` | `'bar'` | Progress bar display format |
110
- | completeChar | `string` | `'█'` | Fill character for completed portion |
111
- | incompleteChar | `string` | `'░'` | Fill character for incomplete portion |
112
- | clearOnComplete | `boolean` | `true` | Whether to clear progress bar on build completion |
113
- | showModuleName | `boolean` | `true` | Whether to show the currently processing module name |
114
- | theme | `ProgressTheme` | - | Custom color theme |
115
-
116
- **ProgressTheme**
117
-
118
- | Property | Type | Description |
119
- | --------------- | -------------------------- | ------------------------ |
120
- | completeColor | `(text: string) => string` | Completed portion color |
121
- | incompleteColor | `(text: string) => string` | Incomplete portion color |
122
- | percentageColor | `(text: string) => string` | Percentage number color |
123
- | phaseColor | `(text: string) => string` | Phase label color |
124
- | moduleColor | `(text: string) => string` | Module name color |
125
-
126
- ```typescript
127
- buildProgress()
128
- buildProgress({ format: 'spinner' })
129
- buildProgress({ format: 'minimal' })
130
- buildProgress({ width: 40, completeChar: '■', incompleteChar: '□', clearOnComplete: false })
131
- buildProgress({
132
- theme: {
133
- completeColor: t => `\x1b[32m${t}\x1b[39m`,
134
- incompleteColor: t => `\x1b[90m${t}\x1b[39m`,
135
- percentageColor: t => `\x1b[1m${t}\x1b[22m`,
136
- phaseColor: t => `\x1b[36m${t}\x1b[39m`,
137
- moduleColor: t => `\x1b[90m${t}\x1b[39m`
138
- }
139
- })
140
- ```
141
-
142
- ---
143
-
144
- ### compressAssets
145
-
146
- Automatically compress files in the output directory after Vite build, supporting both gzip and brotli compression algorithms.
147
-
148
- | Option | Type | Default | Description |
149
- | ------------------ | ---------------------------------- | ----------------------------------------------------------- | -------------------------------------------------- |
150
- | algorithm | `'gzip'` \| `'brotli'` \| `'both'` | `'gzip'` | Compression algorithm |
151
- | threshold | `number` | `1024` | Minimum compression threshold (bytes) |
152
- | deleteOriginalFile | `boolean` | `false` | Whether to delete original files after compression |
153
- | includeExtensions | `string[]` | `['.js', '.css', '.html', '.svg', '.json', '.xml', '.txt']` | File extensions to compress |
154
- | excludeExtensions | `string[]` | `[]` | File extensions to exclude |
155
- | excludePaths | `string[]` | `[]` | Path prefixes to exclude |
156
- | compressionLevel | `number` | `9` | Gzip compression level (1-9) |
157
- | brotliQuality | `number` | `11` | Brotli compression quality (1-11) |
158
- | reportOutput | `string` \| `false` | `'compress-report.json'` | Compression report output path, false to skip |
159
- | parallelLimit | `number` | `10` | Maximum concurrent file compression count |
160
-
161
- ```typescript
162
- compressAssets()
163
- compressAssets({ algorithm: 'brotli' })
164
- compressAssets({ algorithm: 'both', threshold: 2048, compressionLevel: 9, brotliQuality: 11 })
165
- compressAssets({ deleteOriginalFile: true, reportOutput: 'compress-report.json' })
166
- compressAssets({ includeExtensions: ['.js', '.css'], excludePaths: ['assets/images'], parallelLimit: 5 })
167
- ```
168
-
169
- ---
170
-
171
- ### copyFile
172
-
173
- Copy files or directories to specified locations after Vite build is completed, with `enforce: 'post'`.
174
-
175
- | Option | Type | Default | Description |
176
- | ----------- | --------- | ------- | ------------------------------------------ |
177
- | sourceDir | `string` | - | Source directory path (required) |
178
- | targetDir | `string` | - | Target directory path (required) |
179
- | overwrite | `boolean` | `true` | Whether to overwrite existing files |
180
- | recursive | `boolean` | `true` | Whether to recursively copy subdirectories |
181
- | incremental | `boolean` | `true` | Whether to enable incremental copying |
182
-
183
- ```typescript
184
- copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' })
185
- copyFile({ sourceDir: 'src/static', targetDir: 'dist/static', overwrite: false, incremental: false })
186
- ```
187
-
188
- ---
189
-
190
- ### generateRouter
191
-
192
- Automatically generate router configuration files based on uni-app project's `pages.json`.
193
-
194
- | Option | Type | Default | Description |
195
- | -------------------- | --------------------------------------------------------- | ------------------------ | ------------------------------------------------ |
196
- | pagesJsonPath | `string` | `'src/pages.json'` | Path to pages.json file |
197
- | outputPath | `string` | `'src/router.config.ts'` | Output file path |
198
- | outputFormat | `'ts'` \| `'js'` | `'ts'` | Output file format |
199
- | nameStrategy | `'path'` \| `'camelCase'` \| `'pascalCase'` \| `'custom'` | `'camelCase'` | Route name strategy |
200
- | customNameGenerator | `(path: string) => string` | - | Custom route name generator function |
201
- | includeSubPackages | `boolean` | `true` | Whether to include sub-package routes |
202
- | watch | `boolean` | `true` | Whether to watch changes and auto-regenerate |
203
- | metaMapping | `Record<string, string>` | - | Mapping from page style fields to meta |
204
- | exportTypes | `boolean` | `true` | Whether to export type definitions |
205
- | preserveRouteChanges | `boolean` | `true` | Whether to preserve user modifications to routes |
206
-
207
- > Default `metaMapping` is `{ navigationBarTitleText: 'title', requireAuth: 'requireAuth' }`. When `nameStrategy` is `'custom'`, `customNameGenerator` must be provided.
208
-
209
- ```typescript
210
- generateRouter()
211
- generateRouter({ pagesJsonPath: 'pages.json' })
212
- generateRouter({ outputFormat: 'js', outputPath: 'src/router.config.js' })
213
- generateRouter({ nameStrategy: 'pascalCase' })
214
- generateRouter({ nameStrategy: 'custom', customNameGenerator: path => `route_${path.replace(/\//g, '_')}` })
215
- generateRouter({ metaMapping: { navigationBarTitleText: 'title', requireAuth: 'requireAuth', customField: 'custom' } })
216
- ```
217
-
218
- ---
219
-
220
- ### generateVersion
221
-
222
- Automatically generate version numbers during the Vite build process.
223
-
224
- | Option | Type | Default | Description |
225
- | ------------ | --------------------------------------------------------------------------------- | ------------------- | -------------------------------- |
226
- | format | `'timestamp'` \| `'date'` \| `'datetime'` \| `'semver'` \| `'hash'` \| `'custom'` | `'timestamp'` | Version number format |
227
- | customFormat | `string` | - | Custom format template |
228
- | semverBase | `string` | `'1.0.0'` | Semantic version base value |
229
- | outputType | `'file'` \| `'define'` \| `'both'` | `'file'` | Output type |
230
- | outputFile | `string` | `'version.json'` | Output file path |
231
- | defineName | `string` | `'__APP_VERSION__'` | Injected global variable name |
232
- | hashLength | `number` | `8` | Hash length (1-32) |
233
- | prefix | `string` | - | Version number prefix |
234
- | suffix | `string` | - | Version number suffix |
235
- | extra | `Record<string, unknown>` | - | Additional info (JSON file only) |
236
-
237
- **customFormat placeholders:**
238
-
239
- | Placeholder | Description | Example |
240
- | ------------- | ----------------------------------- | --------------- |
241
- | `{YYYY}` | Four-digit year | `2026` |
242
- | `{YY}` | Two-digit year | `26` |
243
- | `{MM}` | Two-digit month | `05` |
244
- | `{DD}` | Two-digit day | `22` |
245
- | `{HH}` | Two-digit hour (24h) | `15` |
246
- | `{mm}` | Two-digit minute | `30` |
247
- | `{ss}` | Two-digit second | `00` |
248
- | `{SSS}` | Three-digit millisecond | `123` |
249
- | `{timestamp}` | Timestamp (milliseconds) | `1779464601000` |
250
- | `{hash}` | Random hash | `a1b2c3d4` |
251
- | `{major}` | Major version (requires semverBase) | `1` |
252
- | `{minor}` | Minor version (requires semverBase) | `0` |
253
- | `{patch}` | Patch version (requires semverBase) | `0` |
254
-
255
- > 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,
256
- > and timestamp.
257
-
258
- ```typescript
259
- generateVersion()
260
- generateVersion({ format: 'date' })
261
- generateVersion({ format: 'semver', semverBase: '2.0.0', prefix: 'v' })
262
- generateVersion({ format: 'custom', customFormat: '{YYYY}.{MM}.{DD}-{hash}', hashLength: 6 })
263
- generateVersion({ outputType: 'define', defineName: '__VERSION__' })
264
- generateVersion({ outputType: 'both', outputFile: 'build-info.json', defineName: '__BUILD_VERSION__', extra: { environment: 'production' } })
265
- ```
266
-
267
- ---
268
-
269
- ### versionUpdateChecker
270
-
271
- Periodically check for version changes at runtime and prompt users to refresh when a new version is detected. Typically used in conjunction with the `generateVersion` plugin.
272
-
273
- **How it works:**
274
-
275
- 1. `generateVersion` generates a version file (`version.json`) or injects a global variable at build time
276
- 2. `versionUpdateChecker` periodically requests the version file at runtime and compares it with the current version
277
- 3. When a version mismatch is detected, a prompt is shown to guide the user to refresh
278
-
279
- | Option | Type | Default | Description |
280
- | ----------------------- | ------------------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------ |
281
- | versionSource | `'define'` \| `'file'` \| `'auto'` | `'auto'` | Current version source |
282
- | defineName | `string` | `'__APP_VERSION__'` | Global variable name in define mode |
283
- | checkUrl | `string` | `'/version.json'` | URL path for version check file |
284
- | checkInterval | `number` | `300000` | Check interval in milliseconds (default 5 minutes) |
285
- | checkOnVisibilityChange | `boolean` | `true` | Whether to check immediately on page visibility change |
286
- | enableInDev | `boolean` | `false` | Whether to enable in development mode |
287
- | promptStyle | `'modal'` \| `'banner'` \| `'toast'` | `'modal'` | Update prompt UI style |
288
- | promptMessage | `string` | `'A new version is available. Refresh now to get the latest?'` | Prompt message text |
289
- | refreshButtonText | `string` | `'Refresh'` | Refresh button text |
290
- | dismissButtonText | `string` | `'Later'` | Dismiss button text |
291
- | customPromptTemplate | `string` | - | Custom HTML template for the prompt UI |
292
- | customStyle | `string` | - | Custom CSS style string |
293
- | onUpdateAvailable | `string` | - | Callback when new version is found (function body string) |
294
- | onRefresh | `string` | - | Callback when user chooses to refresh (function body string) |
295
- | onDismiss | `string` | - | Callback when user chooses to dismiss (function body string) |
296
-
297
- > `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}}`,
298
- > `{{newVersion}}`, `{{refreshButton}}`, `{{dismissButton}}` placeholders. Callbacks are provided as function body strings with available variables: `currentVersion`, `newVersion`.
299
-
300
- ```typescript
301
- generateVersion({ outputType: 'both' })
302
- versionUpdateChecker()
303
- versionUpdateChecker({ versionSource: 'file' })
304
- versionUpdateChecker({ checkInterval: 60000, promptStyle: 'banner' })
305
- versionUpdateChecker({ promptStyle: 'toast' })
306
- versionUpdateChecker({ promptMessage: 'System updated, refresh to experience new features', refreshButtonText: 'Update', dismissButtonText: 'Cancel' })
307
- versionUpdateChecker({ onUpdateAvailable: 'console.log("New version:", newVersion); return true;', onRefresh: 'console.log("User chose to refresh");', onDismiss: 'console.log("User chose to dismiss");' })
308
- versionUpdateChecker({ enableInDev: true })
309
- ```
310
-
311
- ---
312
-
313
- ### htmlInject
314
-
315
- Inject HTML content into target files during Vite build based on configurable rules, supporting multiple injection positions, conditional injection, template variable substitution, and security filtering.
316
-
317
- **Injection positions:**
318
-
319
- | Position | Description |
320
- | ------------------ | ------------------------------------------ |
321
- | `head-start` | Inject after the `<head>` tag opening |
322
- | `head-end` | Inject before the `</head>` closing tag |
323
- | `body-start` | Inject after the `<body>` tag opening |
324
- | `body-end` | Inject before the `</body>` closing tag |
325
- | `before-selector` | Inject before the selector-matched content |
326
- | `after-selector` | Inject after the selector-matched content |
327
- | `replace-selector` | Replace the selector-matched content |
328
-
329
- | Option | Type | Default | Description |
330
- | ------------ | ------------------------ | -------------- | ----------------------------------- |
331
- | targetFile | `string` | `'index.html'` | Target HTML file path or filename |
332
- | rules | `InjectRule[]` | - | Array of injection rules (required) |
333
- | security | `SecurityConfig` | - | Security filtering configuration |
334
- | templateVars | `Record<string, string>` | - | Global template variables |
335
- | logInjection | `boolean` | `true` | Whether to output injection logs |
336
-
337
- **InjectRule**
338
-
339
- | Property | Type | Default | Description |
340
- | -------------------- | ------------------------ | ---------- | --------------------------------------------------------- |
341
- | id | `string` | - | Unique rule identifier |
342
- | content | `string` | - | HTML content to inject |
343
- | position | `InjectPosition` | - | Injection position |
344
- | selector | `string` | - | Selector (required for selector-related positions) |
345
- | selectorMatch | `'string'` \| `'regex'` | `'string'` | Selector matching mode |
346
- | priority | `number` | `100` | Rule priority, lower values execute first |
347
- | condition | `InjectCondition` | - | Injection condition |
348
- | templateVars | `Record<string, string>` | - | Rule-level template variables, override global vars |
349
- | allowScriptInjection | `boolean` | `false` | Whether to allow injecting dangerous content like scripts |
350
-
351
- **SecurityConfig**
352
-
353
- | Property | Type | Default | Description |
354
- | ------------------------ | ---------- | ------- | --------------------------------- |
355
- | blockDangerousTags | `boolean` | `true` | Block dangerous tags |
356
- | blockDangerousAttributes | `boolean` | `true` | Block dangerous attributes |
357
- | allowedTags | `string[]` | - | Whitelist of allowed tags |
358
- | blockedTags | `string[]` | - | Custom list of blocked tags |
359
- | blockedAttributes | `string[]` | - | Custom list of blocked attributes |
360
-
361
- ```typescript
362
- htmlInject({
363
- rules: [
364
- { id: 'meta-description', content: '<meta name="description" content="{{appName}}">', position: 'head-end', templateVars: { appName: 'My Application' } },
365
- { id: 'analytics', content: '<script src="/analytics.js"></script>', position: 'body-end', condition: { type: 'env', value: 'PRODUCTION' }, allowScriptInjection: true }
366
- ]
367
- })
368
- ```
369
-
370
- ---
371
-
372
- ### faviconManager
373
-
374
- Manage website favicon links injection into HTML files, supporting string shorthand config and icon file copying.
375
-
376
- | Option | Type | Default | Description |
377
- | ----------- | -------- | ------- | ------------------------------------------------------ |
378
- | base | `string` | `'/'` | Base path for icon files |
379
- | url | `string` | - | Complete icon URL, takes precedence over base |
380
- | link | `string` | - | Custom complete link tag HTML, highest priority |
381
- | icons | `Icon[]` | - | Custom icon array, supports multiple formats and sizes |
382
- | copyOptions | `object` | - | Icon file copy config (sourceDir, targetDir) |
383
-
384
- **Icon**
385
-
386
- | Property | Type | Description |
387
- | -------- | -------- | ------------------ |
388
- | rel | `string` | Icon relation type |
389
- | href | `string` | Icon URL |
390
- | sizes | `string` | Icon size |
391
- | type | `string` | Icon MIME type |
392
-
393
- ```typescript
394
- faviconManager()
395
- faviconManager('/assets')
396
- faviconManager({
397
- base: '/assets',
398
- icons: [
399
- { rel: 'icon', href: '/favicon.svg', type: 'image/svg+xml' },
400
- { rel: 'icon', href: '/favicon-32x32.png', sizes: '32x32', type: 'image/png' }
401
- ]
402
- })
403
- faviconManager({ link: '<link rel="icon" href="/favicon.svg" type="image/svg+xml" />' })
404
- faviconManager({ base: '/assets', copyOptions: { sourceDir: 'src/assets/icons', targetDir: 'dist/assets/icons' } })
405
- ```
406
-
407
- ---
408
-
409
- ### loadingManager
410
-
411
- Global Loading state management with request interception and white-screen Loading support.
412
-
413
- | Option | Type | Default | Description |
414
- | -------------- | ----------------------------------------------- | ----------------------- | ------------------------------------------ |
415
- | position | `'center'` \| `'top'` \| `'bottom'` | `'center'` | Loading display position |
416
- | defaultText | `string` | `'Loading...'` | Default display text |
417
- | spinnerType | `'spinner'` \| `'dots'` \| `'pulse'` \| `'bar'` | `'spinner'` | Spinner icon type |
418
- | autoBind | `'fetch'` \| `'xhr'` \| `'all'` \| `'none'` | `'none'` | Auto-bind request interception mode |
419
- | globalName | `string` | `'__LOADING_MANAGER__'` | Global variable name injected into browser |
420
- | defaultVisible | `boolean` | `false` | Loading DOM initial visibility state |
421
- | autoHideOn | `'DOMContentLoaded'` \| `'load'` \| `'manual'` | `'DOMContentLoaded'` | Auto-hide timing |
422
- | style | `LoadingStyle` | - | Custom style configuration |
423
- | transition | `TransitionConfig` | - | Transition animation configuration |
424
- | minDisplayTime | `MinDisplayTime` | - | Minimum display time configuration |
425
- | delayShow | `DelayShow` | - | Delay show configuration |
426
- | debounceHide | `DebounceHide` | - | Debounce hide configuration |
427
- | requestFilter | `RequestFilter` | - | Request filter configuration |
428
- | customTemplate | `string` | - | Custom HTML template |
429
- | callbacks | `LoadingCallbacks` | - | Lifecycle callbacks |
430
-
431
- **LoadingStyle**
432
-
433
- | Property | Type | Default | Description |
434
- | ------------------ | --------- | ------------------------- | ---------------------------------------- |
435
- | overlayColor | `string` | `'rgba(255,255,255,0.7)'` | Overlay background color |
436
- | spinnerColor | `string` | `'#4361ee'` | Spinner icon color |
437
- | spinnerSize | `string` | `'40px'` | Spinner icon size |
438
- | textColor | `string` | `'#333'` | Text color |
439
- | textSize | `string` | `'14px'` | Text size |
440
- | zIndex | `number` | `9999` | z-index value |
441
- | pointerEvents | `boolean` | `true` | Whether to enable overlay pointer events |
442
- | backdropBlur | `boolean` | `false` | Whether to enable background blur |
443
- | backdropBlurAmount | `number` | `4` | Background blur amount (px) |
444
- | customClass | `string` | - | Custom CSS class name |
445
- | customStyle | `string` | - | Custom inline style string |
446
-
447
- **Runtime API:**
448
-
449
- ```typescript
450
- window.__LOADING_MANAGER__.show('Loading...')
451
- window.__LOADING_MANAGER__.hide()
452
- window.__LOADING_MANAGER__.forceHide()
453
- window.__LOADING_MANAGER__.toggle()
454
- window.__LOADING_MANAGER__.updateText('Processing...')
455
- window.__LOADING_MANAGER__.isVisible()
456
- window.__LOADING_MANAGER__.getPendingCount()
457
- window.__LOADING_MANAGER__.destroy()
458
- window.__LOADING_MANAGER__.enablePointerEvents()
459
- window.__LOADING_MANAGER__.disablePointerEvents()
460
- window.__LOADING_MANAGER__.togglePointerEvents()
461
- window.__LOADING_MANAGER__.isPointerEventsEnabled()
462
- ```
463
-
464
- ```typescript
465
- loadingManager()
466
- loadingManager({ position: 'top', defaultText: 'Please wait...' })
467
- loadingManager({ spinnerType: 'dots' })
468
- loadingManager({ autoBind: 'fetch', requestFilter: { excludeUrls: [/\/api\/health/], excludeUrlPrefixes: ['http://localhost'] } })
469
- loadingManager({ style: { overlayColor: 'rgba(0,0,0,0.5)', spinnerColor: '#ff6b6b', backdropBlur: true, backdropBlurAmount: 6 } })
470
- loadingManager({ transition: { enabled: true, duration: 300, easing: 'cubic-bezier(0.4,0,0.2,1)' } })
471
- loadingManager({ debounceHide: { enabled: true, duration: 100 } })
472
- loadingManager({ callbacks: { onShow: 'console.log("loading shown")', onBeforeShow: 'return true', onHide: 'console.log("loading hidden")' } })
473
- loadingManager({ customTemplate: '<div class="my-loader"><span data-loading-text></span></div>' })
474
- loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
475
- loadingManager({ defaultVisible: true, autoHideOn: 'manual' })
476
- ```
477
-
478
- ---
65
+ | Plugin | Description |
66
+ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
67
+ | [buildProgress](https://mengxi-studio.github.io/vite-plugin/en/plugins/build-progress.html) | Real-time terminal build progress bar, supports bar / spinner / minimal |
68
+ | [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 |
69
+ | [compressAssets](https://mengxi-studio.github.io/vite-plugin/en/plugins/compress-assets.html) | Asset compression with gzip / brotli / both, concurrent compression and statistics report |
70
+ | [copyFile](https://mengxi-studio.github.io/vite-plugin/en/plugins/copy-file.html) | Copy files or directories after build, supports incremental copying |
71
+ | [envGuard](https://mengxi-studio.github.io/vite-plugin/en/plugins/) | Environment variable validation with type checking, range validation, custom rules and runtime guard |
72
+ | [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 |
73
+ | [generateRouter](https://mengxi-studio.github.io/vite-plugin/en/plugins/generate-router.html) | Auto-generate route config from pages.json (uni-app) |
74
+ | [generateVersion](https://mengxi-studio.github.io/vite-plugin/en/plugins/generate-version.html) | Auto-generate version numbers with file output and global variable injection |
75
+ | [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 |
76
+ | [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 |
77
+ | [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 |
479
78
 
480
79
  ## Plugin Development Framework
481
80
 
482
- ### BasePlugin
483
-
484
- The base class for all built-in plugins, providing core functionality such as configuration management, logging, lifecycle management, and safe execution.
81
+ This package exports a complete plugin development framework to help quickly build custom Vite plugins that follow conventions.
485
82
 
486
83
  ```typescript
487
- import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
84
+ import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
488
85
  import type { Plugin } from 'vite'
489
86
 
490
87
  interface MyPluginOptions {
491
- enabled?: boolean
492
- message?: string
88
+ prefix?: string
493
89
  }
494
90
 
495
91
  class MyPlugin extends BasePlugin<MyPluginOptions> {
496
92
  protected getPluginName() {
497
93
  return 'my-plugin'
498
94
  }
95
+
499
96
  protected getDefaultOptions() {
500
- return { enabled: true, message: 'Hello' }
97
+ return { prefix: '[app]' }
501
98
  }
99
+
502
100
  protected validateOptions() {
503
- this.validator.field('message').string().validate()
101
+ this.validator.field('prefix').string().notEmpty().validate()
504
102
  }
103
+
505
104
  protected addPluginHooks(plugin: Plugin) {
506
- plugin.buildStart = () => {
507
- this.logger.info(this.options.message)
105
+ plugin.writeBundle = {
106
+ order: 'post',
107
+ handler: async () => {
108
+ await this.safeExecute(async () => {
109
+ this.logger.info('Plugin executing...')
110
+ }, 'Execute custom logic')
111
+ }
508
112
  }
509
113
  }
510
114
  }
@@ -512,86 +116,58 @@ class MyPlugin extends BasePlugin<MyPluginOptions> {
512
116
  export const myPlugin = createPluginFactory(MyPlugin)
513
117
  ```
514
118
 
515
- ### Core Components
516
-
517
- | Component | Export Path | Description |
518
- | --------------------- | ------------------------------ | ----------------------------------- |
519
- | `BasePlugin` | `@meng-xi/vite-plugin/factory` | Plugin base class |
520
- | `createPluginFactory` | `@meng-xi/vite-plugin/factory` | Plugin factory function creator |
521
- | `PluginWithInstance` | `@meng-xi/vite-plugin/factory` | Plugin type with instance reference |
522
- | `Logger` | `@meng-xi/vite-plugin/logger` | Log manager (singleton pattern) |
523
- | `Validator` | `@meng-xi/vite-plugin/common` | Fluent API configuration validator |
524
-
525
- ### Common Utilities
119
+ **Core API:**
526
120
 
527
- | Module | Export Path | Description |
528
- | ---------- | ---------------------------------------- | ----------------------------------------------------------------- |
529
- | format | `@meng-xi/vite-plugin/common/format` | Date formatting, name conversion, template parsing, HTML escaping |
530
- | fs | `@meng-xi/vite-plugin/common/fs` | File copying, directory traversal, concurrency control |
531
- | html | `@meng-xi/vite-plugin/common/html` | HTML injection (injectBeforeTag, injectHeadAndBody, etc.) |
532
- | object | `@meng-xi/vite-plugin/common/object` | Deep merge objects |
533
- | script | `@meng-xi/vite-plugin/common/script` | Callback wrapping, script tag detection, identifier validation |
534
- | validation | `@meng-xi/vite-plugin/common/validation` | Global name validation, XSS prevention, enum validation, etc. |
121
+ | API | Description |
122
+ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
123
+ | [`BasePlugin`](https://mengxi-studio.github.io/vite-plugin/en/factory/base-plugin.html) | Plugin base class providing config management, logging, error handling and lifecycle |
124
+ | [`createPluginFactory`](https://mengxi-studio.github.io/vite-plugin/en/factory/create-plugin-factory.html) | Converts a BasePlugin subclass into a Vite plugin function |
125
+ | [`Logger`](https://mengxi-studio.github.io/vite-plugin/en/logger/) | Global singleton log manager with independent log proxies per plugin |
126
+ | [`Validator`](https://mengxi-studio.github.io/vite-plugin/en/factory/) | Chain-style configuration validator for plugin config parameters |
535
127
 
536
- ---
128
+ ## Common Utility Modules
537
129
 
538
- ## Sub-path Exports
539
-
540
- Support importing modules on demand to reduce bundle size:
130
+ Built-in general-purpose utility function library, organized by functional modules, supporting on-demand sub-path imports.
541
131
 
542
132
  ```typescript
543
- import { buildProgress, copyFile, htmlInject, loadingManager, BasePlugin, Logger } from '@meng-xi/vite-plugin'
544
-
545
- import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
546
- import { Logger } from '@meng-xi/vite-plugin/logger'
547
- import { buildProgress, compressAssets, copyFile, generateRouter, generateVersion, versionUpdateChecker, htmlInject, faviconManager, loadingManager } from '@meng-xi/vite-plugin/plugins'
548
- import { Validator, readFileContent, writeFileContent, injectHeadAndBody, deepMerge } from '@meng-xi/vite-plugin/common'
549
-
550
- import type { PluginWithInstance, PluginFactory, BasePluginOptions } from '@meng-xi/vite-plugin/factory'
551
- import type { BuildProgressOptions, CompressAssetsOptions, GenerateVersionOptions, VersionUpdateCheckerOptions, HtmlInjectOptions, FaviconManagerOptions, LoadingManagerOptions } from '@meng-xi/vite-plugin/plugins'
552
- import type { DateFormatOptions } from '@meng-xi/vite-plugin/common/format'
553
- import type { HtmlInjectResult, DualInjectResult } from '@meng-xi/vite-plugin/common/html'
554
- import type { CopyOptions, CopyResult } from '@meng-xi/vite-plugin/common/fs'
555
- ```
133
+ import { formatFileSize } from '@meng-xi/vite-plugin/common/format'
134
+ import { scanDirectory } from '@meng-xi/vite-plugin/common/fs'
135
+ import { calculateGzipSize } from '@meng-xi/vite-plugin/common/compress'
136
+ ```
137
+
138
+ | Sub-path | Description |
139
+ | -------------------------------------------------------------------------------------------- | ----------------------- |
140
+ | [`common/compress`](https://mengxi-studio.github.io/vite-plugin/en/common/compress.html) | Compression utilities |
141
+ | [`common/format`](https://mengxi-studio.github.io/vite-plugin/en/common/format.html) | Formatting utilities |
142
+ | [`common/fs`](https://mengxi-studio.github.io/vite-plugin/en/common/fs.html) | File system utilities |
143
+ | [`common/html`](https://mengxi-studio.github.io/vite-plugin/en/common/html.html) | HTML injection utils |
144
+ | [`common/object`](https://mengxi-studio.github.io/vite-plugin/en/common/object.html) | Object operation utils |
145
+ | [`common/path`](https://mengxi-studio.github.io/vite-plugin/en/common/path.html) | Path handling utils |
146
+ | [`common/script`](https://mengxi-studio.github.io/vite-plugin/en/common/script.html) | Script generation utils |
147
+ | [`common/ui`](https://mengxi-studio.github.io/vite-plugin/en/common/) | Terminal UI utils |
148
+ | [`common/validation`](https://mengxi-studio.github.io/vite-plugin/en/common/validation.html) | Validation utilities |
556
149
 
557
- **All available sub-paths:**
558
-
559
- ```
560
- @meng-xi/vite-plugin
561
- @meng-xi/vite-plugin/factory
562
- @meng-xi/vite-plugin/logger
563
- @meng-xi/vite-plugin/plugins
564
- @meng-xi/vite-plugin/plugins/build-progress
565
- @meng-xi/vite-plugin/plugins/compress-assets
566
- @meng-xi/vite-plugin/plugins/copy-file
567
- @meng-xi/vite-plugin/plugins/favicon-manager
568
- @meng-xi/vite-plugin/plugins/generate-router
569
- @meng-xi/vite-plugin/plugins/generate-version
570
- @meng-xi/vite-plugin/plugins/html-inject
571
- @meng-xi/vite-plugin/plugins/loading-manager
572
- @meng-xi/vite-plugin/plugins/version-update-checker
573
- @meng-xi/vite-plugin/common
574
- @meng-xi/vite-plugin/common/format
575
- @meng-xi/vite-plugin/common/fs
576
- @meng-xi/vite-plugin/common/html
577
- @meng-xi/vite-plugin/common/object
578
- @meng-xi/vite-plugin/common/script
579
- @meng-xi/vite-plugin/common/validation
580
- ```
581
-
582
- ## Changelog
583
-
584
- View [GitHub Releases](https://github.com/MengXi-Studio/vite-plugin/releases)
585
-
586
- ## Contributing
587
-
588
- Contributions are welcome! Please follow these steps:
150
+ ## Sub-path Exports
589
151
 
590
- 1. Fork this project
591
- 2. Create a feature branch: `git checkout -b feature/your-feature`
592
- 3. Commit changes: `git commit -m "feat: your feature description"`
593
- 4. Push branch: `git push origin feature/your-feature`
594
- 5. Create a Pull Request
152
+ | Sub-path | Description |
153
+ | ----------------------------------------------------- | ------------------------------------ |
154
+ | `@meng-xi/vite-plugin` | Main entry (all plugins + framework) |
155
+ | `@meng-xi/vite-plugin/factory` | Plugin development framework |
156
+ | `@meng-xi/vite-plugin/logger` | Log manager |
157
+ | `@meng-xi/vite-plugin/plugins` | All plugins |
158
+ | `@meng-xi/vite-plugin/common` | All utility functions |
159
+ | `@meng-xi/vite-plugin/common/*` | Utility sub-modules |
160
+ | `@meng-xi/vite-plugin/plugins/build-progress` | buildProgress plugin |
161
+ | `@meng-xi/vite-plugin/plugins/bundle-analyzer` | bundleAnalyzer plugin |
162
+ | `@meng-xi/vite-plugin/plugins/compress-assets` | compressAssets plugin |
163
+ | `@meng-xi/vite-plugin/plugins/copy-file` | copyFile plugin |
164
+ | `@meng-xi/vite-plugin/plugins/env-guard` | envGuard plugin |
165
+ | `@meng-xi/vite-plugin/plugins/favicon-manager` | faviconManager plugin |
166
+ | `@meng-xi/vite-plugin/plugins/generate-router` | generateRouter plugin |
167
+ | `@meng-xi/vite-plugin/plugins/generate-version` | generateVersion plugin |
168
+ | `@meng-xi/vite-plugin/plugins/html-inject` | htmlInject plugin |
169
+ | `@meng-xi/vite-plugin/plugins/loading-manager` | loadingManager plugin |
170
+ | `@meng-xi/vite-plugin/plugins/version-update-checker` | versionUpdateChecker plugin |
595
171
 
596
172
  ## License
597
173