@meng-xi/vite-plugin 0.0.6 → 0.0.7

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,404 @@
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 five practical plugins - buildProgress, copyFile, generateRouter, generateVersion, injectIco - covering build progress display, file copying, router generation, version management, and icon
19
+ injection
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
25
+
26
+ ## Documentation
27
+
28
+ View full documentation: [https://mengxi-studio.github.io/vite-plugin/](https://mengxi-studio.github.io/vite-plugin/)
29
+
30
+ ## Installation
31
+
32
+ ::: code-group
33
+
34
+ ```bash [npm]
35
+ npm install @meng-xi/vite-plugin -D
36
+ ```
37
+
38
+ ```bash [yarn]
39
+ yarn add @meng-xi/vite-plugin -D
40
+ ```
41
+
42
+ ```bash [pnpm]
43
+ pnpm add @meng-xi/vite-plugin -D
44
+ ```
45
+
46
+ :::
47
+
48
+ ## Quick Start
49
+
50
+ ### Using Built-in Plugins
51
+
52
+ ```typescript
53
+ import { defineConfig } from 'vite'
54
+ import { buildProgress, copyFile, generateRouter, generateVersion, injectIco } from '@meng-xi/vite-plugin'
55
+
56
+ export default defineConfig({
57
+ plugins: [
58
+ // Build progress bar
59
+ buildProgress(),
60
+
61
+ // Copy files
62
+ copyFile({
63
+ sourceDir: 'src/assets',
64
+ targetDir: 'dist/assets'
65
+ }),
66
+
67
+ // Generate router config (uni-app)
68
+ generateRouter({
69
+ pagesJsonPath: 'src/pages.json',
70
+ outputPath: 'src/router.config.ts'
71
+ }),
72
+
73
+ // Generate version
74
+ generateVersion({
75
+ format: 'datetime',
76
+ outputType: 'both'
77
+ }),
78
+
79
+ // Inject website icon
80
+ injectIco({
81
+ base: '/assets'
82
+ })
83
+ ]
84
+ })
85
+ ```
86
+
87
+ ### Accessing Plugin Instance
88
+
89
+ All built-in plugins return an object with a `pluginInstance` property for accessing internal state:
90
+
91
+ ```typescript
92
+ import type { PluginWithInstance } from '@meng-xi/vite-plugin/factory'
93
+ import type { GenerateRouterOptions } from '@meng-xi/vite-plugin'
94
+
95
+ const routerPlugin = generateRouter({ watch: true }) as PluginWithInstance<GenerateRouterOptions>
96
+
97
+ // Access plugin internals via pluginInstance
98
+ console.log(routerPlugin.pluginInstance?.options)
99
+ ```
100
+
101
+ ### Developing Custom Plugins
102
+
103
+ ```typescript
104
+ import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
105
+ import type { BasePluginOptions, PluginWithInstance } from '@meng-xi/vite-plugin/factory'
106
+ import type { Plugin } from 'vite'
107
+
108
+ interface MyPluginOptions extends BasePluginOptions {
109
+ path: string
110
+ }
111
+
112
+ class MyPlugin extends BasePlugin<MyPluginOptions> {
113
+ protected getDefaultOptions() {
114
+ return { path: './default' }
115
+ }
116
+
117
+ protected validateOptions(): void {
118
+ this.validator.field('path').required().string().validate()
119
+ }
120
+
121
+ protected getPluginName(): string {
122
+ return 'my-plugin'
123
+ }
124
+
125
+ protected addPluginHooks(plugin: Plugin): void {
126
+ plugin.buildStart = () => {
127
+ this.logger.info(`Plugin started with path: ${this.options.path}`)
128
+ }
129
+ }
130
+
131
+ protected destroy(): void {
132
+ super.destroy()
133
+ // Custom cleanup logic, e.g. close connections, stop watchers
134
+ }
135
+ }
136
+
137
+ export const myPlugin = createPluginFactory(MyPlugin)
138
+ ```
139
+
140
+ ## Plugin Development Framework
141
+
142
+ ### BasePlugin Core Concepts
143
+
144
+ `BasePlugin` is the base class for all plugins, providing complete lifecycle management and development conventions:
145
+
146
+ #### Lifecycle
147
+
148
+ | Phase | Method | Description |
149
+ | ----------------- | ------------------ | -------------------------------------------------------------- |
150
+ | Initialization | `constructor` | Merge options, initialize logger and validator |
151
+ | Config Resolution | `onConfigResolved` | Called when Vite config is resolved |
152
+ | Hook Registration | `addPluginHooks` | Register Vite plugin hooks |
153
+ | Destroy | `destroy` | Automatically called during `closeBundle` for resource cleanup |
154
+
155
+ #### Automatic Hook Composition
156
+
157
+ The `toPlugin()` method automatically composes the following hooks:
158
+
159
+ - **configResolved** - Base class `onConfigResolved` runs first, then subclass hook
160
+ - **closeBundle** - Subclass hook runs first, then base class `destroy`
161
+
162
+ > Subclasses don't need to manually register `closeBundle` hooks for cleanup — just override the `destroy()` method.
163
+
164
+ #### Required Methods
165
+
166
+ | Method | Description |
167
+ | ------------------------ | --------------------- |
168
+ | `getPluginName()` | Return plugin name |
169
+ | `addPluginHooks(plugin)` | Add Vite plugin hooks |
170
+
171
+ #### Optional Methods
172
+
173
+ | Method | Default Behavior | Description |
174
+ | -------------------------- | ----------------- | ------------------------------------------- |
175
+ | `getDefaultOptions()` | Returns `{}` | Provide plugin default options |
176
+ | `validateOptions()` | No validation | Validate configuration parameters |
177
+ | `getEnforce()` | `undefined` | Plugin execution order (`'pre'` / `'post'`) |
178
+ | `onConfigResolved(config)` | Store config | Config resolved callback |
179
+ | `destroy()` | Unregister logger | Cleanup logic when plugin is destroyed |
180
+
181
+ #### Built-in Properties
182
+
183
+ | Property | Type | Description |
184
+ | ------------ | ------------------------ | ----------------------------- |
185
+ | `options` | `Required<T>` | Merged complete configuration |
186
+ | `logger` | `PluginLogger` | Plugin logger |
187
+ | `validator` | `Validator<T>` | Configuration validator |
188
+ | `viteConfig` | `ResolvedConfig \| null` | Resolved Vite configuration |
189
+
190
+ #### Error Handling Strategy
191
+
192
+ Control error behavior via the `errorStrategy` configuration option:
193
+
194
+ - `'throw'` (default) - Log error and throw exception, halting the build
195
+ - `'log'` - Log error but don't throw, continue execution
196
+ - `'ignore'` - Log error but don't throw, continue execution
197
+
198
+ Wrap error-prone operations with `safeExecute` / `safeExecuteSync`:
199
+
200
+ ```typescript
201
+ const result = await this.safeExecute(async () => {
202
+ return await someAsyncOperation()
203
+ }, 'Execute async operation')
204
+ ```
205
+
206
+ ### createPluginFactory
207
+
208
+ Create plugin factory functions with optional normalizer support:
209
+
210
+ ```typescript
211
+ // Basic usage
212
+ const myPlugin = createPluginFactory(MyPlugin)
213
+
214
+ // With normalizer (supports shorthand string config)
215
+ const myPlugin = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { path: opt } : opt))
216
+
217
+ // Usage with shorthand
218
+ myPlugin('./custom-path')
219
+ ```
220
+
221
+ ### Logger
222
+
223
+ Global singleton log manager providing independent log control for each plugin:
224
+
225
+ ```typescript
226
+ import { Logger } from '@meng-xi/vite-plugin/logger'
227
+
228
+ // Create logger (usually called automatically by BasePlugin)
229
+ Logger.create({ name: 'my-plugin', enabled: true })
230
+
231
+ // Unregister plugin log config (automatically called on plugin destroy)
232
+ Logger.unregister('my-plugin')
233
+
234
+ // Destroy singleton (for test scenarios)
235
+ Logger.destroy()
236
+ ```
237
+
238
+ Log output format:
239
+
240
+ ```
241
+ ℹ️ [@meng-xi/vite-plugin:my-plugin] Info message
242
+ [@meng-xi/vite-plugin:my-plugin] Success message
243
+ ⚠️ [@meng-xi/vite-plugin:my-plugin] Warning message
244
+ [@meng-xi/vite-plugin:my-plugin] Error message
245
+ ```
246
+
247
+ ## Built-in Plugins
248
+
249
+ ### buildProgress
250
+
251
+ Display real-time build progress bar in terminal during Vite build, supporting three display formats.
252
+
253
+ | Option | Type | Default | Description |
254
+ | --------------- | ------------------------------------- | ------- | ---------------------------------------------------- |
255
+ | width | number | 30 | Progress bar width (characters) |
256
+ | format | `'bar'` \| `'spinner'` \| `'minimal'` | 'bar' | Progress bar display format |
257
+ | completeChar | string | '█' | Fill character for completed portion |
258
+ | incompleteChar | string | '' | Fill character for incomplete portion |
259
+ | clearOnComplete | boolean | true | Whether to clear progress bar on build completion |
260
+ | showModuleName | boolean | true | Whether to show the currently processing module name |
261
+ | theme | [ProgressTheme](#progresstheme) | - | Custom color theme |
262
+
263
+ **ProgressTheme**
264
+
265
+ | Property | Type | Description |
266
+ | --------------- | -------------------------- | ------------------------ |
267
+ | completeColor | `(text: string) => string` | Completed portion color |
268
+ | incompleteColor | `(text: string) => string` | Incomplete portion color |
269
+ | percentageColor | `(text: string) => string` | Percentage number color |
270
+ | phaseColor | `(text: string) => string` | Phase label color |
271
+ | moduleColor | `(text: string) => string` | Module name color |
272
+
273
+ ```typescript
274
+ // Default bar format
275
+ buildProgress()
276
+
277
+ // Spinner format
278
+ buildProgress({ format: 'spinner' })
279
+
280
+ // Minimal format
281
+ buildProgress({ format: 'minimal' })
282
+
283
+ // Custom appearance
284
+ buildProgress({
285
+ width: 40,
286
+ completeChar: '■',
287
+ incompleteChar: '□',
288
+ clearOnComplete: false
289
+ })
290
+ ```
291
+
292
+ ### copyFile
293
+
294
+ Copy files or directories to specified locations after Vite build is completed.
295
+
296
+ | Option | Type | Default | Description |
297
+ | ----------- | ------- | ------- | ------------------------------------------ |
298
+ | sourceDir | string | - | Source directory path (required) |
299
+ | targetDir | string | - | Target directory path (required) |
300
+ | overwrite | boolean | true | Whether to overwrite existing files |
301
+ | recursive | boolean | true | Whether to recursively copy subdirectories |
302
+ | incremental | boolean | true | Whether to enable incremental copying |
303
+
304
+ ### generateRouter
305
+
306
+ Automatically generate router configuration files based on uni-app project's `pages.json`.
307
+
308
+ | Option | Type | Default | Description |
309
+ | -------------------- | --------------------------------------------------------- | ---------------------- | ------------------------------------------------ |
310
+ | pagesJsonPath | string | 'src/pages.json' | Path to pages.json file |
311
+ | outputPath | string | 'src/router.config.ts' | Output file path |
312
+ | outputFormat | `'ts'` \| `'js'` | 'ts' | Output file format |
313
+ | nameStrategy | `'path'` \| `'camelCase'` \| `'pascalCase'` \| `'custom'` | 'camelCase' | Route name strategy |
314
+ | customNameGenerator | `(path: string) => string` | - | Custom route name generator function |
315
+ | includeSubPackages | boolean | true | Whether to include sub-package routes |
316
+ | watch | boolean | true | Whether to watch changes and auto-regenerate |
317
+ | metaMapping | `Record<string, string>` | - | Mapping from page style fields to meta |
318
+ | exportTypes | boolean | true | Whether to export type definitions |
319
+ | preserveRouteChanges | boolean | true | Whether to preserve user modifications to routes |
320
+
321
+ ### generateVersion
322
+
323
+ Automatically generate version numbers during the Vite build process.
324
+
325
+ | Option | Type | Default | Description |
326
+ | ------------ | --------------------------------------------------------------------------------- | ----------------- | ------------------------------ |
327
+ | format | `'timestamp'` \| `'date'` \| `'datetime'` \| `'semver'` \| `'hash'` \| `'custom'` | 'timestamp' | Version format |
328
+ | customFormat | string | - | Custom format template |
329
+ | semverBase | string | '1.0.0' | Semantic version base |
330
+ | outputType | `'file'` \| `'define'` \| `'both'` | 'file' | Output type |
331
+ | outputFile | string | 'version.json' | Output file path |
332
+ | defineName | string | '**APP_VERSION**' | Global variable name to inject |
333
+ | hashLength | number | 8 | Hash length (1-32) |
334
+ | prefix | string | - | Version number prefix |
335
+ | suffix | string | - | Version number suffix |
336
+ | extra | `Record<string, unknown>` | - | Extra info (JSON file only) |
337
+
338
+ ### injectIco
339
+
340
+ Inject website icon links into the head of HTML files during the Vite build process.
341
+
342
+ | Option | Type | Default | Description |
343
+ | ----------- | ------ | ------- | ------------------------------- |
344
+ | base | string | '/' | Base path for icon files |
345
+ | url | string | - | Complete URL for the icon |
346
+ | link | string | - | Custom complete link tag HTML |
347
+ | icons | Icon[] | - | Custom icon array |
348
+ | copyOptions | object | - | Icon file copying configuration |
349
+
350
+ `Icon` interface definition:
351
+
352
+ | Property | Type | Required | Description |
353
+ | -------- | ------ | -------- | ------------------ |
354
+ | rel | string | Yes | Icon relation type |
355
+ | href | string | Yes | Icon URL |
356
+ | sizes | string | No | Icon sizes |
357
+ | type | string | No | Icon MIME type |
358
+
359
+ `copyOptions` interface definition:
360
+
361
+ | Property | Type | Required | Default | Description |
362
+ | --------- | ------- | -------- | ------- | --------------------------- |
363
+ | sourceDir | string | Yes | - | Icon source directory |
364
+ | targetDir | string | Yes | - | Icon target directory |
365
+ | overwrite | boolean | No | true | Whether to overwrite files |
366
+ | recursive | boolean | No | true | Whether to copy recursively |
367
+
368
+ ## Sub-path Exports
369
+
370
+ Support importing modules on demand to reduce bundle size:
371
+
372
+ ```typescript
373
+ // Full import
374
+ import { buildProgress, copyFile, BasePlugin, Logger } from '@meng-xi/vite-plugin'
375
+
376
+ // Module-level import
377
+ import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
378
+ import { Logger } from '@meng-xi/vite-plugin/logger'
379
+ import { buildProgress, copyFile, generateRouter } from '@meng-xi/vite-plugin/plugins'
380
+ import { Validator, readFileContent, writeFileContent } from '@meng-xi/vite-plugin/common'
381
+
382
+ // Type imports (on-demand type definitions from sub-paths)
383
+ import type { PluginWithInstance, PluginFactory, BasePluginOptions } from '@meng-xi/vite-plugin/factory'
384
+ import type { BuildProgressOptions, GenerateVersionOptions, InjectIcoOptions, Icon } from '@meng-xi/vite-plugin/plugins'
385
+ import type { DateFormatOptions } from '@meng-xi/vite-plugin/common'
386
+ ```
387
+
388
+ ## Changelog
389
+
390
+ See [GitHub Releases](https://github.com/MengXi-Studio/vite-plugin/releases)
391
+
392
+ ## Contributing
393
+
394
+ Contributions are welcome! Please follow these steps:
395
+
396
+ 1. Fork the repository
397
+ 2. Create a feature branch: `git checkout -b feature/your-feature`
398
+ 3. Commit changes: `git commit -m "feat: your feature description"`
399
+ 4. Push to branch: `git push origin feature/your-feature`
400
+ 5. Create a Pull Request
401
+
402
+ ## License
403
+
404
+ [MIT](LICENSE)