@meng-xi/vite-plugin 0.0.6 → 0.0.8

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.
package/README-en.md CHANGED
@@ -1,343 +1,540 @@
1
- **English** | [中文](./README.md)
2
-
3
- <div align="center">
4
- <a href="https://github.com/MengXi-Studio/vite-plugin">
5
- <img alt="MengXi Studio Logo" width="215" src="https://github.com/MengXi-Studio/vite-plugin/blob/master/packages/docs/src/public/logo.png">
6
- </a>
7
- <br>
8
- <h1>@meng-xi/vite-plugin</h1>
9
- <p>A toolkit providing practical plugins for Vite, also a complete plugin development framework</p>
10
-
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
- ![npm](https://img.shields.io/npm/dt/@meng-xi/vite-plugin?color=green)
13
-
14
- </div>
15
-
16
- ## Features
17
-
18
- - **Ready to Use** - Provides practical plugins for file copying, router generation, version management, icon injection
19
- - **Plugin Development Framework** - Exports core components like BasePlugin, Logger, Validator for building custom plugins
20
- - **Complete Lifecycle** - Supports initialization, config resolution, destroy lifecycle management with automatic hook composition
21
- - **Type Safe** - Complete TypeScript type definitions with configuration validators ensuring parameter correctness
22
- - **Flexible Configuration** - All plugins support detailed configuration to meet diverse scenario requirements
23
- - **Safe Execution** - Built-in error handling strategies (throw / log / ignore) for unified exception management
24
-
25
- ## Documentation
26
-
27
- View full documentation: [https://mengxi-studio.github.io/vite-plugin/](https://mengxi-studio.github.io/vite-plugin/)
28
-
29
- ## Installation
30
-
31
- ```bash
32
- # npm
33
- npm install @meng-xi/vite-plugin -D
34
-
35
- # yarn
36
- yarn add @meng-xi/vite-plugin -D
37
-
38
- # pnpm
39
- pnpm add @meng-xi/vite-plugin -D
40
- ```
41
-
42
- ## Quick Start
43
-
44
- ### Using Built-in Plugins
45
-
46
- ```typescript
47
- import { defineConfig } from 'vite'
48
- import { copyFile, generateRouter, generateVersion, injectIco } from '@meng-xi/vite-plugin'
49
-
50
- export default defineConfig({
51
- plugins: [
52
- // Copy files
53
- copyFile({
54
- sourceDir: 'src/assets',
55
- targetDir: 'dist/assets'
56
- }),
57
-
58
- // Generate router config (uni-app)
59
- generateRouter({
60
- pagesJsonPath: 'src/pages.json',
61
- outputPath: 'src/router.config.ts'
62
- }),
63
-
64
- // Generate version
65
- generateVersion({
66
- format: 'datetime',
67
- outputType: 'both'
68
- }),
69
-
70
- // Inject website icon
71
- injectIco({
72
- base: '/assets'
73
- })
74
- ]
75
- })
76
- ```
77
-
78
- ### Accessing Plugin Instance
79
-
80
- All built-in plugins return an object with a `pluginInstance` property for accessing internal state:
81
-
82
- ```typescript
83
- import type { PluginWithInstance } from '@meng-xi/vite-plugin/factory'
84
- import type { GenerateRouterOptions } from '@meng-xi/vite-plugin'
85
-
86
- const routerPlugin = generateRouter({ watch: true }) as PluginWithInstance<GenerateRouterOptions>
87
-
88
- // Access plugin internals via pluginInstance
89
- console.log(routerPlugin.pluginInstance?.options)
90
- ```
91
-
92
- ### Developing Custom Plugins
93
-
94
- ```typescript
95
- import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
96
- import type { BasePluginOptions, PluginWithInstance } from '@meng-xi/vite-plugin/factory'
97
- import type { Plugin } from 'vite'
98
-
99
- interface MyPluginOptions extends BasePluginOptions {
100
- path: string
101
- }
102
-
103
- class MyPlugin extends BasePlugin<MyPluginOptions> {
104
- protected getDefaultOptions() {
105
- return { path: './default' }
106
- }
107
-
108
- protected validateOptions(): void {
109
- this.validator.field('path').required().string().validate()
110
- }
111
-
112
- protected getPluginName(): string {
113
- return 'my-plugin'
114
- }
115
-
116
- protected addPluginHooks(plugin: Plugin): void {
117
- plugin.buildStart = () => {
118
- this.logger.info(`Plugin started with path: ${this.options.path}`)
119
- }
120
- }
121
-
122
- protected destroy(): void {
123
- super.destroy()
124
- // Custom cleanup logic, e.g. close connections, stop watchers
125
- }
126
- }
127
-
128
- export const myPlugin = createPluginFactory(MyPlugin)
129
- ```
130
-
131
- ## Plugin Development Framework
132
-
133
- ### BasePlugin Core Concepts
134
-
135
- `BasePlugin` is the base class for all plugins, providing complete lifecycle management and development conventions:
136
-
137
- #### Lifecycle
138
-
139
- | Phase | Method | Description |
140
- | ----------------- | ------------------ | -------------------------------------------------------------- |
141
- | Initialization | `constructor` | Merge options, initialize logger and validator |
142
- | Config Resolution | `onConfigResolved` | Called when Vite config is resolved |
143
- | Hook Registration | `addPluginHooks` | Register Vite plugin hooks |
144
- | Destroy | `destroy` | Automatically called during `closeBundle` for resource cleanup |
145
-
146
- #### Automatic Hook Composition
147
-
148
- The `toPlugin()` method automatically composes the following hooks:
149
-
150
- - **configResolved** - Base class `onConfigResolved` runs first, then subclass hook
151
- - **closeBundle** - Subclass hook runs first, then base class `destroy`
152
-
153
- > Subclasses don't need to manually register `closeBundle` hooks for cleanup — just override the `destroy()` method.
154
-
155
- #### Required Methods
156
-
157
- | Method | Description |
158
- | ------------------------ | --------------------- |
159
- | `getPluginName()` | Return plugin name |
160
- | `addPluginHooks(plugin)` | Add Vite plugin hooks |
161
-
162
- #### Optional Methods
163
-
164
- | Method | Default Behavior | Description |
165
- | -------------------------- | ----------------- | ------------------------------------------- |
166
- | `getDefaultOptions()` | Returns `{}` | Provide plugin default options |
167
- | `validateOptions()` | No validation | Validate configuration parameters |
168
- | `getEnforce()` | `undefined` | Plugin execution order (`'pre'` / `'post'`) |
169
- | `onConfigResolved(config)` | Store config | Config resolved callback |
170
- | `destroy()` | Unregister logger | Cleanup logic when plugin is destroyed |
171
-
172
- #### Built-in Properties
173
-
174
- | Property | Type | Description |
175
- | ------------ | ------------------------ | ----------------------------- |
176
- | `options` | `Required<T>` | Merged complete configuration |
177
- | `logger` | `PluginLogger` | Plugin logger |
178
- | `validator` | `Validator<T>` | Configuration validator |
179
- | `viteConfig` | `ResolvedConfig \| null` | Resolved Vite configuration |
180
-
181
- #### Error Handling Strategy
182
-
183
- Control error behavior via the `errorStrategy` configuration option:
184
-
185
- - `'throw'` (default) - Log error and throw exception, halting the build
186
- - `'log'` - Log error but don't throw, continue execution
187
- - `'ignore'` - Log error but don't throw, continue execution
188
-
189
- Wrap error-prone operations with `safeExecute` / `safeExecuteSync`:
190
-
191
- ```typescript
192
- const result = await this.safeExecute(async () => {
193
- return await someAsyncOperation()
194
- }, 'Execute async operation')
195
- ```
196
-
197
- ### createPluginFactory
198
-
199
- Create plugin factory functions with optional normalizer support:
200
-
201
- ```typescript
202
- // Basic usage
203
- const myPlugin = createPluginFactory(MyPlugin)
204
-
205
- // With normalizer (supports shorthand string config)
206
- const myPlugin = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { path: opt } : opt))
207
-
208
- // Usage with shorthand
209
- myPlugin('./custom-path')
210
- ```
211
-
212
- ### Logger
213
-
214
- Global singleton log manager providing independent log control for each plugin:
215
-
216
- ```typescript
217
- import { Logger } from '@meng-xi/vite-plugin/logger'
218
-
219
- // Create logger (usually called automatically by BasePlugin)
220
- Logger.create({ name: 'my-plugin', enabled: true })
221
-
222
- // Unregister plugin log config (automatically called on plugin destroy)
223
- Logger.unregister('my-plugin')
224
-
225
- // Destroy singleton (for test scenarios)
226
- Logger.destroy()
227
- ```
228
-
229
- Log output format:
230
-
231
- ```
232
- ℹ️ [@meng-xi/vite-plugin:my-plugin] Info message
233
- [@meng-xi/vite-plugin:my-plugin] Success message
234
- ⚠️ [@meng-xi/vite-plugin:my-plugin] Warning message
235
- ❌ [@meng-xi/vite-plugin:my-plugin] Error message
236
- ```
237
-
238
- ## Built-in Plugins
239
-
240
- ### copyFile
241
-
242
- Copy files or directories to specified locations after Vite build is completed.
243
-
244
- | Option | Type | Default | Description |
245
- | ----------- | ------- | ------- | ------------------------------------------ |
246
- | sourceDir | string | - | Source directory path (required) |
247
- | targetDir | string | - | Target directory path (required) |
248
- | overwrite | boolean | true | Whether to overwrite existing files |
249
- | recursive | boolean | true | Whether to recursively copy subdirectories |
250
- | incremental | boolean | true | Whether to enable incremental copying |
251
-
252
- ### generateRouter
253
-
254
- Automatically generate router configuration files based on uni-app project's `pages.json`.
255
-
256
- | Option | Type | Default | Description |
257
- | -------------------- | ------------------------------------------------- | ---------------------- | ------------------------------------------------ |
258
- | pagesJsonPath | string | 'src/pages.json' | Path to pages.json file |
259
- | outputPath | string | 'src/router.config.ts' | Output file path |
260
- | outputFormat | 'ts' \| 'js' | 'ts' | Output file format |
261
- | nameStrategy | 'path' \| 'camelCase' \| 'pascalCase' \| 'custom' | 'camelCase' | Route name strategy |
262
- | customNameGenerator | (path: string) => string | - | Custom route name generator function |
263
- | includeSubPackages | boolean | true | Whether to include sub-package routes |
264
- | watch | boolean | true | Whether to watch changes and auto-regenerate |
265
- | metaMapping | Record\<string, string\> | - | Mapping from page style fields to meta |
266
- | exportTypes | boolean | true | Whether to export type definitions |
267
- | preserveRouteChanges | boolean | true | Whether to preserve user modifications to routes |
268
-
269
- ### generateVersion
270
-
271
- Automatically generate version numbers during the Vite build process.
272
-
273
- | Option | Type | Default | Description |
274
- | ------------ | --------------------------------------------------------------------- | ----------------- | ------------------------------ |
275
- | format | 'timestamp' \| 'date' \| 'datetime' \| 'semver' \| 'hash' \| 'custom' | 'timestamp' | Version format |
276
- | customFormat | string | - | Custom format template |
277
- | semverBase | string | '1.0.0' | Semantic version base |
278
- | outputType | 'file' \| 'define' \| 'both' | 'file' | Output type |
279
- | outputFile | string | 'version.json' | Output file path |
280
- | defineName | string | '**APP_VERSION**' | Global variable name to inject |
281
- | hashLength | number | 8 | Hash length (1-32) |
282
- | prefix | string | - | Version number prefix |
283
- | suffix | string | - | Version number suffix |
284
- | extra | Record\<string, unknown\> | - | Extra info (JSON file only) |
285
-
286
- ### injectIco
287
-
288
- Inject website icon links into the head of HTML files during the Vite build process.
289
-
290
- | Option | Type | Default | Description |
291
- | ----------- | ------ | ------- | ------------------------------- |
292
- | base | string | '/' | Base path for icon files |
293
- | url | string | - | Complete URL for the icon |
294
- | link | string | - | Custom complete link tag HTML |
295
- | icons | Icon[] | - | Custom icon array |
296
- | copyOptions | object | - | Icon file copying configuration |
297
-
298
- `Icon` interface definition:
299
-
300
- | Property | Type | Required | Description |
301
- | -------- | ------ | -------- | ------------------ |
302
- | rel | string | Yes | Icon relation type |
303
- | href | string | Yes | Icon URL |
304
- | sizes | string | No | Icon sizes |
305
- | type | string | No | Icon MIME type |
306
-
307
- ## Sub-path Exports
308
-
309
- Support importing modules on demand to reduce bundle size:
310
-
311
- ```typescript
312
- // Full import
313
- import { copyFile, BasePlugin, Logger } from '@meng-xi/vite-plugin'
314
-
315
- // Module-level import
316
- import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
317
- import { Logger } from '@meng-xi/vite-plugin/logger'
318
- import { copyFile, generateRouter } from '@meng-xi/vite-plugin/plugins'
319
- import { Validator, readFileContent, writeFileContent } from '@meng-xi/vite-plugin/common'
320
-
321
- // Type imports (on-demand type definitions from sub-paths)
322
- import type { PluginWithInstance, PluginFactory, BasePluginOptions } from '@meng-xi/vite-plugin/factory'
323
- import type { GenerateVersionOptions, InjectIcoOptions, Icon } from '@meng-xi/vite-plugin/plugins'
324
- import type { DateFormatOptions } from '@meng-xi/vite-plugin/common'
325
- ```
326
-
327
- ## Changelog
328
-
329
- See [GitHub Releases](https://github.com/MengXi-Studio/vite-plugin/releases)
330
-
331
- ## Contributing
332
-
333
- Contributions are welcome! Please follow these steps:
334
-
335
- 1. Fork the repository
336
- 2. Create a feature branch: `git checkout -b feature/your-feature`
337
- 3. Commit changes: `git commit -m "feat: your feature description"`
338
- 4. Push to branch: `git push origin feature/your-feature`
339
- 5. Create a Pull Request
340
-
341
- ## License
342
-
343
- [MIT](LICENSE)
1
+ **English** | [中文](./README.md)
2
+
3
+ <div align="center">
4
+ <a href="https://github.com/MengXi-Studio/vite-plugin">
5
+ <img alt="MengXi Studio Logo" width="215" src="https://github.com/MengXi-Studio/vite-plugin/blob/master/packages/docs/src/public/logo.png">
6
+ </a>
7
+ <br>
8
+ <h1>@meng-xi/vite-plugin</h1>
9
+ <p>A toolkit providing practical plugins for Vite, also a complete plugin development framework</p>
10
+
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
+ ![npm](https://img.shields.io/npm/dt/@meng-xi/vite-plugin?color=green)
13
+
14
+ </div>
15
+
16
+ ## Features
17
+
18
+ - **Ready to Use** - Provides 6 practical plugins covering build progress display, file copying, router generation, version management, icon injection, and global Loading state management
19
+ - **Plugin Development Framework** - Exports core components like BasePlugin, Logger, Validator for building custom Vite plugins
20
+ - **Complete Lifecycle** - Supports initialization, config resolution, destroy lifecycle management with automatic hook composition
21
+ - **Type Safe** - Complete TypeScript type definitions with configuration validators ensuring parameter correctness
22
+ - **Flexible Configuration** - All plugins support detailed configuration to meet diverse scenario requirements
23
+ - **Safe Execution** - Built-in error handling strategies (throw / log / ignore) for unified exception management
24
+
25
+ ## Documentation
26
+
27
+ View full documentation: [https://mengxi-studio.github.io/vite-plugin/](https://mengxi-studio.github.io/vite-plugin/)
28
+
29
+ ## Installation
30
+
31
+ ::: code-group
32
+
33
+ ```bash [npm]
34
+ npm install @meng-xi/vite-plugin -D
35
+ ```
36
+
37
+ ```bash [yarn]
38
+ yarn add @meng-xi/vite-plugin -D
39
+ ```
40
+
41
+ ```bash [pnpm]
42
+ pnpm add @meng-xi/vite-plugin -D
43
+ ```
44
+
45
+ :::
46
+
47
+ ## Quick Start
48
+
49
+ ### Using Built-in Plugins
50
+
51
+ ```typescript
52
+ import { defineConfig } from 'vite'
53
+ import { buildProgress, copyFile, generateRouter, generateVersion, injectIco, injectLoading } from '@meng-xi/vite-plugin'
54
+
55
+ export default defineConfig({
56
+ plugins: [
57
+ // Build progress bar
58
+ buildProgress(),
59
+
60
+ // Copy files
61
+ copyFile({
62
+ sourceDir: 'src/assets',
63
+ targetDir: 'dist/assets'
64
+ }),
65
+
66
+ // Generate router config (uni-app)
67
+ generateRouter({
68
+ pagesJsonPath: 'src/pages.json',
69
+ outputPath: 'src/router.config.ts'
70
+ }),
71
+
72
+ // Generate version
73
+ generateVersion({
74
+ format: 'datetime',
75
+ outputType: 'both'
76
+ }),
77
+
78
+ // Inject website icon
79
+ injectIco({
80
+ base: '/assets'
81
+ }),
82
+
83
+ // Inject global Loading
84
+ injectLoading({
85
+ defaultVisible: true,
86
+ autoHideOn: 'DOMContentLoaded'
87
+ })
88
+ ]
89
+ })
90
+ ```
91
+
92
+ ### Accessing Plugin Instance
93
+
94
+ All built-in plugins return an object with a `pluginInstance` property for accessing internal state:
95
+
96
+ ```typescript
97
+ import type { PluginWithInstance } from '@meng-xi/vite-plugin/factory'
98
+ import type { GenerateRouterOptions } from '@meng-xi/vite-plugin'
99
+
100
+ const routerPlugin = generateRouter({ watch: true }) as PluginWithInstance<GenerateRouterOptions>
101
+
102
+ // Access plugin internals via pluginInstance
103
+ console.log(routerPlugin.pluginInstance?.options)
104
+ ```
105
+
106
+ ### Developing Custom Plugins
107
+
108
+ ```typescript
109
+ import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
110
+ import type { BasePluginOptions, PluginWithInstance } from '@meng-xi/vite-plugin/factory'
111
+ import type { Plugin } from 'vite'
112
+
113
+ interface MyPluginOptions extends BasePluginOptions {
114
+ path: string
115
+ }
116
+
117
+ class MyPlugin extends BasePlugin<MyPluginOptions> {
118
+ protected getDefaultOptions() {
119
+ return { path: './default' }
120
+ }
121
+
122
+ protected validateOptions(): void {
123
+ this.validator.field('path').required().string().validate()
124
+ }
125
+
126
+ protected getPluginName(): string {
127
+ return 'my-plugin'
128
+ }
129
+
130
+ protected addPluginHooks(plugin: Plugin): void {
131
+ plugin.buildStart = () => {
132
+ this.logger.info(`Plugin started with path: ${this.options.path}`)
133
+ }
134
+ }
135
+
136
+ protected destroy(): void {
137
+ super.destroy()
138
+ // Custom cleanup logic, e.g. close connections, stop watchers
139
+ }
140
+ }
141
+
142
+ export const myPlugin = createPluginFactory(MyPlugin)
143
+ ```
144
+
145
+ ## Plugin Development Framework
146
+
147
+ ### BasePlugin Core Concepts
148
+
149
+ `BasePlugin` is the base class for all plugins, providing complete lifecycle management and development conventions:
150
+
151
+ #### Lifecycle
152
+
153
+ | Phase | Method | Description |
154
+ | ----------------- | ------------------ | -------------------------------------------------------------- |
155
+ | Initialization | `constructor` | Merge options, initialize logger and validator |
156
+ | Config Resolution | `onConfigResolved` | Called when Vite config is resolved |
157
+ | Hook Registration | `addPluginHooks` | Register Vite plugin hooks |
158
+ | Destroy | `destroy` | Automatically called during `closeBundle` for resource cleanup |
159
+
160
+ #### Automatic Hook Composition
161
+
162
+ The `toPlugin()` method automatically composes the following hooks:
163
+
164
+ - **configResolved** - Base class `onConfigResolved` runs first, then subclass hook
165
+ - **closeBundle** - Subclass hook runs first, then base class `destroy`
166
+
167
+ > Subclasses don't need to manually register `closeBundle` hooks for cleanup just override the `destroy()` method.
168
+
169
+ #### Required Methods
170
+
171
+ | Method | Description |
172
+ | ------------------------ | --------------------- |
173
+ | `getPluginName()` | Return plugin name |
174
+ | `addPluginHooks(plugin)` | Add Vite plugin hooks |
175
+
176
+ #### Optional Methods
177
+
178
+ | Method | Default Behavior | Description |
179
+ | -------------------------- | ----------------- | ------------------------------------------- |
180
+ | `getDefaultOptions()` | Returns `{}` | Provide plugin default options |
181
+ | `validateOptions()` | No validation | Validate configuration parameters |
182
+ | `getEnforce()` | `undefined` | Plugin execution order (`'pre'` / `'post'`) |
183
+ | `onConfigResolved(config)` | Store config | Config resolved callback |
184
+ | `destroy()` | Unregister logger | Cleanup logic when plugin is destroyed |
185
+
186
+ #### Built-in Properties
187
+
188
+ | Property | Type | Description |
189
+ | ------------ | ------------------------ | ----------------------------- |
190
+ | `options` | `Required<T>` | Merged complete configuration |
191
+ | `logger` | `PluginLogger` | Plugin logger |
192
+ | `validator` | `Validator<T>` | Configuration validator |
193
+ | `viteConfig` | `ResolvedConfig \| null` | Resolved Vite configuration |
194
+
195
+ #### Error Handling Strategy
196
+
197
+ Control error behavior via the `errorStrategy` configuration option:
198
+
199
+ - `'throw'` (default) - Log error and throw exception, halting the build
200
+ - `'log'` - Log error but don't throw, continue execution
201
+ - `'ignore'` - Log error but don't throw, continue execution
202
+
203
+ Wrap error-prone operations with `safeExecute` / `safeExecuteSync`:
204
+
205
+ ```typescript
206
+ const result = await this.safeExecute(async () => {
207
+ return await someAsyncOperation()
208
+ }, 'Execute async operation')
209
+ ```
210
+
211
+ ### createPluginFactory
212
+
213
+ Create plugin factory functions with optional normalizer support:
214
+
215
+ ```typescript
216
+ // Basic usage
217
+ const myPlugin = createPluginFactory(MyPlugin)
218
+
219
+ // With normalizer (supports shorthand string config)
220
+ const myPlugin = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { path: opt } : opt))
221
+
222
+ // Usage with shorthand
223
+ myPlugin('./custom-path')
224
+ ```
225
+
226
+ ### Logger
227
+
228
+ Global singleton log manager providing independent log control for each plugin:
229
+
230
+ ```typescript
231
+ import { Logger } from '@meng-xi/vite-plugin/logger'
232
+
233
+ // Create logger (usually called automatically by BasePlugin)
234
+ Logger.create({ name: 'my-plugin', enabled: true })
235
+
236
+ // Unregister plugin log config (automatically called on plugin destroy)
237
+ Logger.unregister('my-plugin')
238
+
239
+ // Destroy singleton (for test scenarios)
240
+ Logger.destroy()
241
+ ```
242
+
243
+ Log output format:
244
+
245
+ ```
246
+ ℹ️ [@meng-xi/vite-plugin:my-plugin] Info message
247
+ [@meng-xi/vite-plugin:my-plugin] Success message
248
+ ⚠️ [@meng-xi/vite-plugin:my-plugin] Warning message
249
+ [@meng-xi/vite-plugin:my-plugin] Error message
250
+ ```
251
+
252
+ ## Built-in Plugins
253
+
254
+ | Plugin | Description |
255
+ | --------------- | ----------------------------------------------------------------------------------------- |
256
+ | buildProgress | Real-time build progress bar in terminal, supports bar / spinner / minimal |
257
+ | copyFile | Copy files or directories after build, supports incremental copying |
258
+ | generateRouter | Auto-generate router config from pages.json (uni-app) |
259
+ | generateVersion | Auto-generate version numbers, supports file output and global variable injection |
260
+ | injectIco | Inject website icon links into HTML files |
261
+ | injectLoading | Inject global Loading state management with request interception and white-screen Loading |
262
+
263
+ ### buildProgress
264
+
265
+ Display real-time build progress bar in terminal during Vite build, supporting three display formats.
266
+
267
+ | Option | Type | Default | Description |
268
+ | --------------- | ------------------------------------- | ------- | ---------------------------------------------------- |
269
+ | width | `number` | `30` | Progress bar width (characters) |
270
+ | format | `'bar'` \| `'spinner'` \| `'minimal'` | `'bar'` | Progress bar display format |
271
+ | completeChar | `string` | `'█'` | Fill character for completed portion |
272
+ | incompleteChar | `string` | `'░'` | Fill character for incomplete portion |
273
+ | clearOnComplete | `boolean` | `true` | Whether to clear progress bar on build completion |
274
+ | showModuleName | `boolean` | `true` | Whether to show the currently processing module name |
275
+ | theme | `ProgressTheme` | - | Custom color theme |
276
+
277
+ **ProgressTheme**
278
+
279
+ | Property | Type | Description |
280
+ | --------------- | -------------------------- | ------------------------ |
281
+ | completeColor | `(text: string) => string` | Completed portion color |
282
+ | incompleteColor | `(text: string) => string` | Incomplete portion color |
283
+ | percentageColor | `(text: string) => string` | Percentage number color |
284
+ | phaseColor | `(text: string) => string` | Phase label color |
285
+ | moduleColor | `(text: string) => string` | Module name color |
286
+
287
+ ```typescript
288
+ // Default bar format
289
+ buildProgress()
290
+
291
+ // Spinner format
292
+ buildProgress({ format: 'spinner' })
293
+
294
+ // Minimal format
295
+ buildProgress({ format: 'minimal' })
296
+
297
+ // Custom appearance
298
+ buildProgress({
299
+ width: 40,
300
+ completeChar: '■',
301
+ incompleteChar: '□',
302
+ clearOnComplete: false
303
+ })
304
+ ```
305
+
306
+ ### copyFile
307
+
308
+ Copy files or directories to specified locations after Vite build is completed.
309
+
310
+ | Option | Type | Default | Description |
311
+ | ----------- | --------- | ------- | ------------------------------------------ |
312
+ | sourceDir | `string` | - | Source directory path (required) |
313
+ | targetDir | `string` | - | Target directory path (required) |
314
+ | overwrite | `boolean` | `true` | Whether to overwrite existing files |
315
+ | recursive | `boolean` | `true` | Whether to recursively copy subdirectories |
316
+ | incremental | `boolean` | `true` | Whether to enable incremental copying |
317
+
318
+ ### generateRouter
319
+
320
+ Automatically generate router configuration files based on uni-app project's `pages.json`.
321
+
322
+ | Option | Type | Default | Description |
323
+ | -------------------- | --------------------------------------------------------- | ------------------------ | ------------------------------------------------ |
324
+ | pagesJsonPath | `string` | `'src/pages.json'` | Path to pages.json file |
325
+ | outputPath | `string` | `'src/router.config.ts'` | Output file path |
326
+ | outputFormat | `'ts'` \| `'js'` | `'ts'` | Output file format |
327
+ | nameStrategy | `'path'` \| `'camelCase'` \| `'pascalCase'` \| `'custom'` | `'camelCase'` | Route name strategy |
328
+ | customNameGenerator | `(path: string) => string` | - | Custom route name generator function |
329
+ | includeSubPackages | `boolean` | `true` | Whether to include sub-package routes |
330
+ | watch | `boolean` | `true` | Whether to watch changes and auto-regenerate |
331
+ | metaMapping | `Record<string, string>` | - | Mapping from page style fields to meta |
332
+ | exportTypes | `boolean` | `true` | Whether to export type definitions |
333
+ | preserveRouteChanges | `boolean` | `true` | Whether to preserve user modifications to routes |
334
+
335
+ ### generateVersion
336
+
337
+ Automatically generate version numbers during the Vite build process.
338
+
339
+ | Option | Type | Default | Description |
340
+ | ------------ | --------------------------------------------------------------------------------- | ------------------- | ------------------------------ |
341
+ | format | `'timestamp'` \| `'date'` \| `'datetime'` \| `'semver'` \| `'hash'` \| `'custom'` | `'timestamp'` | Version format |
342
+ | customFormat | `string` | - | Custom format template |
343
+ | semverBase | `string` | `'1.0.0'` | Semantic version base |
344
+ | outputType | `'file'` \| `'define'` \| `'both'` | `'file'` | Output type |
345
+ | outputFile | `string` | `'version.json'` | Output file path |
346
+ | defineName | `string` | `'__APP_VERSION__'` | Global variable name to inject |
347
+ | hashLength | `number` | `8` | Hash length (1-32) |
348
+ | prefix | `string` | - | Version number prefix |
349
+ | suffix | `string` | - | Version number suffix |
350
+ | extra | `Record<string, unknown>` | - | Extra info (JSON file only) |
351
+
352
+ ### injectIco
353
+
354
+ Inject website icon links into the head of HTML files during the Vite build process.
355
+
356
+ | Option | Type | Default | Description |
357
+ | ----------- | -------- | ------- | ------------------------------- |
358
+ | base | `string` | `'/'` | Base path for icon files |
359
+ | url | `string` | - | Complete URL for the icon |
360
+ | link | `string` | - | Custom complete link tag HTML |
361
+ | icons | `Icon[]` | - | Custom icon array |
362
+ | copyOptions | `object` | - | Icon file copying configuration |
363
+
364
+ `Icon` interface definition:
365
+
366
+ | Property | Type | Required | Description |
367
+ | -------- | -------- | -------- | ------------------ |
368
+ | rel | `string` | Yes | Icon relation type |
369
+ | href | `string` | Yes | Icon URL |
370
+ | sizes | `string` | No | Icon sizes |
371
+ | type | `string` | No | Icon MIME type |
372
+
373
+ `copyOptions` interface definition:
374
+
375
+ | Property | Type | Required | Default | Description |
376
+ | --------- | --------- | -------- | ------- | --------------------------- |
377
+ | sourceDir | `string` | Yes | - | Icon source directory |
378
+ | targetDir | `string` | Yes | - | Icon target directory |
379
+ | overwrite | `boolean` | No | `true` | Whether to overwrite files |
380
+ | recursive | `boolean` | No | `true` | Whether to copy recursively |
381
+
382
+ ### injectLoading
383
+
384
+ Inject global Loading state management with XHR/Fetch request interception, white-screen Loading, custom styles, and lifecycle callbacks.
385
+
386
+ | Option | Type | Default | Description |
387
+ | -------------- | ----------------------------------------------- | ----------------------- | ------------------------------------------------------- |
388
+ | position | `'center'` \| `'top'` \| `'bottom'` | `'center'` | Loading display position |
389
+ | defaultText | `string` | `'Loading...'` | Default display text |
390
+ | spinnerType | `'spinner'` \| `'dots'` \| `'pulse'` \| `'bar'` | `'spinner'` | Spinner icon type |
391
+ | style | `LoadingStyle` | - | Custom style configuration |
392
+ | transition | `TransitionConfig` | `{ enabled: true }` | Transition animation configuration |
393
+ | minDisplayTime | `MinDisplayTime` | `{ enabled: true }` | Minimum display time configuration |
394
+ | delayShow | `DelayShow` | `{ enabled: true }` | Delayed show configuration |
395
+ | debounceHide | `DebounceHide` | `{ enabled: false }` | Debounced hide configuration |
396
+ | autoBind | `'fetch'` \| `'xhr'` \| `'all'` \| `'none'` | `'none'` | Auto-bind request interception mode |
397
+ | requestFilter | `RequestFilter` | - | Request filter configuration |
398
+ | globalName | `string` | `'__LOADING_MANAGER__'` | Global variable name injected into browser |
399
+ | customTemplate | `string` | - | Custom HTML template (must include `data-loading-text`) |
400
+ | defaultVisible | `boolean` | `false` | Whether initially visible (white-screen Loading) |
401
+ | autoHideOn | `'DOMContentLoaded'` \| `'load'` \| `'manual'` | `'DOMContentLoaded'` | Auto-hide timing (requires `defaultVisible: true`) |
402
+ | callbacks | `LoadingCallbacks` | - | Lifecycle callbacks |
403
+
404
+ **LoadingStyle**
405
+
406
+ | Property | Type | Default | Description |
407
+ | ------------------ | --------- | ------------------------- | ------------------------------- |
408
+ | overlayColor | `string` | `'rgba(255,255,255,0.7)'` | Overlay background color |
409
+ | spinnerColor | `string` | `'#4361ee'` | Spinner color |
410
+ | spinnerSize | `string` | `'40px'` | Spinner size |
411
+ | textColor | `string` | `'#333'` | Text color |
412
+ | textSize | `string` | `'14px'` | Text size |
413
+ | customClass | `string` | - | Custom CSS class name |
414
+ | customStyle | `string` | - | Custom inline style string |
415
+ | zIndex | `number` | `9999` | z-index value |
416
+ | pointerEvents | `boolean` | `false` | Whether to allow click-through |
417
+ | backdropBlur | `boolean` | `false` | Whether to enable backdrop blur |
418
+ | backdropBlurAmount | `number` | `4` | Backdrop blur amount (px) |
419
+
420
+ **TransitionConfig**
421
+
422
+ | Property | Type | Default | Description |
423
+ | -------- | --------- | ------------ | ---------------------------- |
424
+ | enabled | `boolean` | `true` | Whether to enable transition |
425
+ | duration | `number` | `200` | Transition duration (ms) |
426
+ | easing | `string` | `'ease-out'` | Easing function |
427
+
428
+ **MinDisplayTime**
429
+
430
+ | Property | Type | Default | Description |
431
+ | -------- | --------- | ------- | ------------------------- |
432
+ | enabled | `boolean` | `true` | Whether to enable |
433
+ | duration | `number` | `300` | Minimum display time (ms) |
434
+
435
+ **DelayShow**
436
+
437
+ | Property | Type | Default | Description |
438
+ | -------- | --------- | ------- | ------------------------------------------------------------------------------ |
439
+ | enabled | `boolean` | `true` | Whether to enable |
440
+ | duration | `number` | `200` | Delay duration (ms); if request completes within this time, Loading won't show |
441
+
442
+ **DebounceHide**
443
+
444
+ | Property | Type | Default | Description |
445
+ | -------- | --------- | ------- | ----------------------- |
446
+ | enabled | `boolean` | `false` | Whether to enable |
447
+ | duration | `number` | `100` | Debounce wait time (ms) |
448
+
449
+ **RequestFilter**
450
+
451
+ | Property | Type | Description |
452
+ | ------------------ | ---------- | --------------------------------------------------------------------- |
453
+ | excludeUrls | `RegExp[]` | Array of URL regex patterns to exclude |
454
+ | includeUrls | `RegExp[]` | Array of URL regex patterns to include (higher priority than exclude) |
455
+ | excludeMethods | `string[]` | Array of HTTP methods to exclude |
456
+ | excludeUrlPrefixes | `string[]` | Array of URL prefixes to exclude (prefix matching, more efficient) |
457
+
458
+ **LoadingCallbacks**
459
+
460
+ Callbacks are provided as **function body strings** (injected into browser at build time, function references cannot be passed).
461
+
462
+ | Property | Type | Description |
463
+ | ------------ | -------- | ----------------------------------------------- |
464
+ | onBeforeShow | `string` | Before show callback, `return false` to prevent |
465
+ | onShow | `string` | After show callback |
466
+ | onBeforeHide | `string` | Before hide callback, `return false` to prevent |
467
+ | onHide | `string` | After hide callback |
468
+ | onDestroy | `string` | On destroy callback |
469
+
470
+ **LoadingManager API**
471
+
472
+ Access via `window.__LOADING_MANAGER__`:
473
+
474
+ | Method | Description |
475
+ | ------------------- | ------------------------------------------------------------------- |
476
+ | `show(text?)` | Show Loading, optionally pass text |
477
+ | `hide()` | Hide Loading (subject to min display time and debounce constraints) |
478
+ | `forceHide()` | Force hide, ignoring min display time and debounce |
479
+ | `destroy()` | Destroy instance and restore original interceptors |
480
+ | `updateText(t)` | Update text content |
481
+ | `isVisible()` | Get whether Loading is currently visible |
482
+ | `getPendingCount()` | Get the number of pending requests |
483
+
484
+ ```typescript
485
+ // White-screen Loading: visible on page load, auto-hide on DOMContentLoaded
486
+ injectLoading({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
487
+
488
+ // Auto-intercept all requests
489
+ injectLoading({ autoBind: 'all' })
490
+
491
+ // Custom styles + request filtering
492
+ injectLoading({
493
+ style: { overlayColor: 'rgba(0,0,0,0.5)', spinnerColor: '#fff' },
494
+ autoBind: 'fetch',
495
+ requestFilter: { excludeUrls: [/\/api\/health/] }
496
+ })
497
+
498
+ // Manual control
499
+ injectLoading()
500
+ window.__LOADING_MANAGER__.show('Saving...')
501
+ window.__LOADING_MANAGER__.hide()
502
+ ```
503
+
504
+ ## Sub-path Exports
505
+
506
+ Support importing modules on demand to reduce bundle size:
507
+
508
+ ```typescript
509
+ // Full import
510
+ import { buildProgress, copyFile, injectLoading, BasePlugin, Logger } from '@meng-xi/vite-plugin'
511
+
512
+ // Module-level import
513
+ import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
514
+ import { Logger } from '@meng-xi/vite-plugin/logger'
515
+ import { buildProgress, copyFile, generateRouter, injectLoading } from '@meng-xi/vite-plugin/plugins'
516
+ import { Validator, readFileContent, writeFileContent } from '@meng-xi/vite-plugin/common'
517
+
518
+ // Type imports (on-demand type definitions from sub-paths)
519
+ import type { PluginWithInstance, PluginFactory, BasePluginOptions } from '@meng-xi/vite-plugin/factory'
520
+ import type { BuildProgressOptions, GenerateVersionOptions, InjectIcoOptions, InjectLoadingOptions, Icon } from '@meng-xi/vite-plugin/plugins'
521
+ import type { DateFormatOptions } from '@meng-xi/vite-plugin/common'
522
+ ```
523
+
524
+ ## Changelog
525
+
526
+ See [GitHub Releases](https://github.com/MengXi-Studio/vite-plugin/releases)
527
+
528
+ ## Contributing
529
+
530
+ Contributions are welcome! Please follow these steps:
531
+
532
+ 1. Fork the repository
533
+ 2. Create a feature branch: `git checkout -b feature/your-feature`
534
+ 3. Commit changes: `git commit -m "feat: your feature description"`
535
+ 4. Push to branch: `git push origin feature/your-feature`
536
+ 5. Create a Pull Request
537
+
538
+ ## License
539
+
540
+ [MIT](LICENSE)