@meng-xi/vite-plugin 0.1.1 → 0.1.2

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.md CHANGED
@@ -15,7 +15,7 @@
15
15
 
16
16
  ## 特性
17
17
 
18
- - **开箱即用** - 提供 8 个实用插件,覆盖构建进度展示、文件复制、路由生成、版本管理、版本更新检查、HTML 注入、图标注入、全局 Loading 状态管理等常见场景
18
+ - **开箱即用** - 提供 9 个实用插件,覆盖构建进度展示、构建产物压缩、文件复制、路由生成、版本管理、版本更新检查、HTML 注入、图标注入、全局 Loading 状态管理等常见场景
19
19
  - **插件开发框架** - 导出 BasePlugin、Logger、Validator 等核心组件,快速构建符合规范的自定义 Vite 插件
20
20
  - **完整生命周期** - 支持初始化、配置解析、销毁等生命周期管理,自动组合钩子逻辑
21
21
  - **类型安全** - 完整的 TypeScript 类型定义,配置验证器确保参数正确性
@@ -46,53 +46,21 @@ pnpm add @meng-xi/vite-plugin -D
46
46
 
47
47
  ```typescript
48
48
  import { defineConfig } from 'vite'
49
- import { buildProgress, copyFile, generateRouter, generateVersion, versionUpdateChecker, htmlInject, faviconManager, loadingManager } from '@meng-xi/vite-plugin'
49
+ import { buildProgress, compressAssets, copyFile, generateRouter, generateVersion, versionUpdateChecker, htmlInject, faviconManager, loadingManager } from '@meng-xi/vite-plugin'
50
50
 
51
51
  export default defineConfig({
52
52
  plugins: [
53
- // 构建进度条
54
53
  buildProgress(),
55
-
56
- // 复制文件
57
- copyFile({
58
- sourceDir: 'src/assets',
59
- targetDir: 'dist/assets'
60
- }),
61
-
62
- // 生成路由配置(uni-app)
63
- generateRouter({
64
- pagesJsonPath: 'src/pages.json',
65
- outputPath: 'src/router.config.ts'
66
- }),
67
-
68
- // 生成版本号
69
- generateVersion({
70
- format: 'datetime',
71
- outputType: 'both'
72
- }),
73
-
74
- // 版本更新检查(配合 generateVersion 使用)
54
+ compressAssets({ algorithm: 'gzip' }),
55
+ copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' }),
56
+ generateRouter({ pagesJsonPath: 'src/pages.json', outputPath: 'src/router.config.ts' }),
57
+ generateVersion({ format: 'datetime', outputType: 'both' }),
75
58
  versionUpdateChecker(),
76
-
77
- // HTML 内容注入
78
59
  htmlInject({
79
- rules: [
80
- {
81
- id: 'meta-description',
82
- content: '<meta name="description" content="My App">',
83
- position: 'head-end'
84
- }
85
- ]
60
+ rules: [{ id: 'meta-description', content: '<meta name="description" content="My App">', position: 'head-end' }]
86
61
  }),
87
-
88
- // 注入网站图标(支持字符串简写)
89
62
  faviconManager('/assets'),
90
-
91
- // 全局 Loading 状态管理
92
- loadingManager({
93
- defaultVisible: true,
94
- autoHideOn: 'DOMContentLoaded'
95
- })
63
+ loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
96
64
  ]
97
65
  })
98
66
  ```
@@ -106,8 +74,6 @@ import type { PluginWithInstance } from '@meng-xi/vite-plugin/factory'
106
74
  import type { GenerateRouterOptions } from '@meng-xi/vite-plugin'
107
75
 
108
76
  const routerPlugin = generateRouter({ watch: true }) as PluginWithInstance<GenerateRouterOptions>
109
-
110
- // 通过 pluginInstance 访问插件内部
111
77
  console.log(routerPlugin.pluginInstance?.options)
112
78
  ```
113
79
 
@@ -116,6 +82,7 @@ console.log(routerPlugin.pluginInstance?.options)
116
82
  | 插件 | 说明 |
117
83
  | -------------------- | --------------------------------------------------------------- |
118
84
  | buildProgress | 终端实时构建进度条,支持 bar / spinner / minimal |
85
+ | compressAssets | 构建产物压缩,支持 gzip / brotli / both,并发压缩和统计报告 |
119
86
  | copyFile | 构建完成后复制文件或目录,支持增量复制 |
120
87
  | generateRouter | 根据 pages.json 自动生成路由配置(uni-app) |
121
88
  | generateVersion | 自动生成版本号,支持文件输出和全局变量注入 |
@@ -124,6 +91,8 @@ console.log(routerPlugin.pluginInstance?.options)
124
91
  | faviconManager | 管理网站图标(favicon)链接注入到 HTML 文件,支持字符串简写配置 |
125
92
  | loadingManager | 全局 Loading 状态管理,支持请求拦截和白屏 Loading |
126
93
 
94
+ ---
95
+
127
96
  ### buildProgress
128
97
 
129
98
  在终端实时显示 Vite 构建进度条,支持三种显示格式。
@@ -154,24 +123,10 @@ console.log(routerPlugin.pluginInstance?.options)
154
123
  | moduleColor | `(text: string) => string` | 模块名称颜色 |
155
124
 
156
125
  ```typescript
157
- // 默认进度条格式
158
126
  buildProgress()
159
-
160
- // 旋转动画格式
161
127
  buildProgress({ format: 'spinner' })
162
-
163
- // 精简格式
164
128
  buildProgress({ format: 'minimal' })
165
-
166
- // 自定义外观
167
- buildProgress({
168
- width: 40,
169
- completeChar: '■',
170
- incompleteChar: '□',
171
- clearOnComplete: false
172
- })
173
-
174
- // 自定义颜色主题
129
+ buildProgress({ width: 40, completeChar: '■', incompleteChar: '□', clearOnComplete: false })
175
130
  buildProgress({
176
131
  theme: {
177
132
  completeColor: t => `\x1b[32m${t}\x1b[39m`,
@@ -183,6 +138,35 @@ buildProgress({
183
138
  })
184
139
  ```
185
140
 
141
+ ---
142
+
143
+ ### compressAssets
144
+
145
+ 在 Vite 构建完成后自动压缩输出目录中的文件,支持 gzip 和 brotli 两种压缩算法。
146
+
147
+ | 选项 | 类型 | 默认值 | 描述 |
148
+ | ------------------ | ---------------------------------- | ----------------------------------------------------------- | ------------------------------ |
149
+ | algorithm | `'gzip'` \| `'brotli'` \| `'both'` | `'gzip'` | 压缩算法 |
150
+ | threshold | `number` | `1024` | 最小压缩阈值(字节) |
151
+ | deleteOriginalFile | `boolean` | `false` | 压缩后是否删除原始文件 |
152
+ | includeExtensions | `string[]` | `['.js', '.css', '.html', '.svg', '.json', '.xml', '.txt']` | 需要压缩的文件扩展名 |
153
+ | excludeExtensions | `string[]` | `[]` | 需要排除的文件扩展名 |
154
+ | excludePaths | `string[]` | `[]` | 需要排除的路径前缀 |
155
+ | compressionLevel | `number` | `9` | gzip 压缩级别(1-9) |
156
+ | brotliQuality | `number` | `11` | brotli 压缩质量(1-11) |
157
+ | reportOutput | `string` \| `false` | `'compress-report.json'` | 压缩报告输出路径,false 不生成 |
158
+ | parallelLimit | `number` | `10` | 并发压缩最大文件数 |
159
+
160
+ ```typescript
161
+ compressAssets()
162
+ compressAssets({ algorithm: 'brotli' })
163
+ compressAssets({ algorithm: 'both', threshold: 2048, compressionLevel: 9, brotliQuality: 11 })
164
+ compressAssets({ deleteOriginalFile: true, reportOutput: 'compress-report.json' })
165
+ compressAssets({ includeExtensions: ['.js', '.css'], excludePaths: ['assets/images'], parallelLimit: 5 })
166
+ ```
167
+
168
+ ---
169
+
186
170
  ### copyFile
187
171
 
188
172
  在 Vite 构建完成后复制文件或目录到指定位置,执行时机为 `enforce: 'post'`。
@@ -196,21 +180,12 @@ buildProgress({
196
180
  | incremental | `boolean` | `true` | 是否启用增量复制 |
197
181
 
198
182
  ```typescript
199
- // 基本使用
200
- copyFile({
201
- sourceDir: 'src/assets',
202
- targetDir: 'dist/assets'
203
- })
204
-
205
- // 禁用覆盖和增量复制
206
- copyFile({
207
- sourceDir: 'src/static',
208
- targetDir: 'dist/static',
209
- overwrite: false,
210
- incremental: false
211
- })
183
+ copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' })
184
+ copyFile({ sourceDir: 'src/static', targetDir: 'dist/static', overwrite: false, incremental: false })
212
185
  ```
213
186
 
187
+ ---
188
+
214
189
  ### generateRouter
215
190
 
216
191
  根据 uni-app 项目的 `pages.json` 自动生成路由配置文件。
@@ -228,37 +203,19 @@ copyFile({
228
203
  | exportTypes | `boolean` | `true` | 是否导出类型定义 |
229
204
  | preserveRouteChanges | `boolean` | `true` | 是否保留用户对 routes 的修改 |
230
205
 
231
- > 默认 `metaMapping` 为 `{ navigationBarTitleText: 'title', requireAuth: 'requireAuth' }`,自动将页面样式字段映射到路由元信息。当 `nameStrategy` 为 `'custom'` 时,必须提供 `customNameGenerator`。
206
+ > 默认 `metaMapping` 为 `{ navigationBarTitleText: 'title', requireAuth: 'requireAuth' }`。当 `nameStrategy` 为 `'custom'` 时,必须提供 `customNameGenerator`。
232
207
 
233
208
  ```typescript
234
- // 基本使用
235
209
  generateRouter()
236
-
237
- // 自定义 pages.json 路径
238
210
  generateRouter({ pagesJsonPath: 'pages.json' })
239
-
240
- // 输出 JavaScript 文件
241
211
  generateRouter({ outputFormat: 'js', outputPath: 'src/router.config.js' })
242
-
243
- // 使用帕斯卡命名策略
244
212
  generateRouter({ nameStrategy: 'pascalCase' })
245
-
246
- // 自定义路由名称生成
247
- generateRouter({
248
- nameStrategy: 'custom',
249
- customNameGenerator: path => `route_${path.replace(/\//g, '_')}`
250
- })
251
-
252
- // 自定义元信息映射
253
- generateRouter({
254
- metaMapping: {
255
- navigationBarTitleText: 'title',
256
- requireAuth: 'requireAuth',
257
- customField: 'custom'
258
- }
259
- })
213
+ generateRouter({ nameStrategy: 'custom', customNameGenerator: path => `route_${path.replace(/\//g, '_')}` })
214
+ generateRouter({ metaMapping: { navigationBarTitleText: 'title', requireAuth: 'requireAuth', customField: 'custom' } })
260
215
  ```
261
216
 
217
+ ---
218
+
262
219
  ### generateVersion
263
220
 
264
221
  在 Vite 构建过程中自动生成版本号。
@@ -297,34 +254,16 @@ generateRouter({
297
254
  > 当 `format` 为 `'custom'` 时,必须提供 `customFormat`。当 `outputType` 为 `'define'` 或 `'both'` 时,同时注入 `{defineName}_INFO` 全局变量,包含版本号、构建时间、时间戳等完整信息。
298
255
 
299
256
  ```typescript
300
- // 时间戳格式(默认)
301
257
  generateVersion()
302
-
303
- // 日期格式
304
258
  generateVersion({ format: 'date' })
305
-
306
- // 语义化版本格式
307
259
  generateVersion({ format: 'semver', semverBase: '2.0.0', prefix: 'v' })
308
-
309
- // 自定义格式
310
- generateVersion({
311
- format: 'custom',
312
- customFormat: '{YYYY}.{MM}.{DD}-{hash}',
313
- hashLength: 6
314
- })
315
-
316
- // 注入到代码中
260
+ generateVersion({ format: 'custom', customFormat: '{YYYY}.{MM}.{DD}-{hash}', hashLength: 6 })
317
261
  generateVersion({ outputType: 'define', defineName: '__VERSION__' })
318
-
319
- // 同时输出文件和注入代码
320
- generateVersion({
321
- outputType: 'both',
322
- outputFile: 'build-info.json',
323
- defineName: '__BUILD_VERSION__',
324
- extra: { environment: 'production' }
325
- })
262
+ generateVersion({ outputType: 'both', outputFile: 'build-info.json', defineName: '__BUILD_VERSION__', extra: { environment: 'production' } })
326
263
  ```
327
264
 
265
+ ---
266
+
328
267
  ### versionUpdateChecker
329
268
 
330
269
  在运行时定期检查版本号变更,发现新版本时提示用户刷新页面。通常与 `generateVersion` 插件配合使用。
@@ -357,40 +296,18 @@ generateVersion({
357
296
  > `{{message}}`、`{{currentVersion}}`、`{{newVersion}}`、`{{refreshButton}}`、`{{dismissButton}}` 占位符。回调以函数体字符串形式提供,可用变量:`currentVersion`、`newVersion`。
358
297
 
359
298
  ```typescript
360
- // 基本使用(配合 generateVersion)
361
299
  generateVersion({ outputType: 'both' })
362
300
  versionUpdateChecker()
363
-
364
- // 仅从版本文件读取
365
301
  versionUpdateChecker({ versionSource: 'file' })
366
-
367
- // 自定义检查间隔和提示样式
368
- versionUpdateChecker({
369
- checkInterval: 60000,
370
- promptStyle: 'banner'
371
- })
372
-
373
- // 底部轻提示
302
+ versionUpdateChecker({ checkInterval: 60000, promptStyle: 'banner' })
374
303
  versionUpdateChecker({ promptStyle: 'toast' })
375
-
376
- // 自定义提示文本
377
- versionUpdateChecker({
378
- promptMessage: '系统已更新,建议刷新体验新功能',
379
- refreshButtonText: '更新',
380
- dismissButtonText: '取消'
381
- })
382
-
383
- // 自定义回调
384
- versionUpdateChecker({
385
- onUpdateAvailable: 'console.log("新版本:", newVersion); return true;',
386
- onRefresh: 'console.log("用户选择刷新");',
387
- onDismiss: 'console.log("用户选择忽略");'
388
- })
389
-
390
- // 开发环境也启用(调试用)
304
+ versionUpdateChecker({ promptMessage: '系统已更新,建议刷新体验新功能', refreshButtonText: '更新', dismissButtonText: '取消' })
305
+ versionUpdateChecker({ onUpdateAvailable: 'console.log("新版本:", newVersion); return true;', onRefresh: 'console.log("用户选择刷新");', onDismiss: 'console.log("用户选择忽略");' })
391
306
  versionUpdateChecker({ enableInDev: true })
392
307
  ```
393
308
 
309
+ ---
310
+
394
311
  ### htmlInject
395
312
 
396
313
  在 Vite 构建过程中根据配置规则将 HTML 内容注入到目标文件中,支持多种注入位置、条件注入、模板变量替换和安全过滤。
@@ -417,163 +334,97 @@ versionUpdateChecker({ enableInDev: true })
417
334
 
418
335
  **InjectRule**
419
336
 
420
- | 属性 | 类型 | 默认值 | 描述 |
421
- | -------------------- | ------------------------ | ---------- | ----------------------------------- |
422
- | id | `string` | - | 规则唯一标识,用于日志和调试 |
423
- | content | `string` | - | 要注入的 HTML 内容(必填) |
424
- | position | `InjectPosition` | - | 注入位置(必填) |
425
- | selector | `string` | - | 选择器字符串(selector 位置时必填) |
426
- | selectorMatch | `'string'` \| `'regex'` | `'string'` | 选择器匹配模式 |
427
- | priority | `number` | `100` | 优先级,数值越小越先执行 |
428
- | condition | `InjectCondition` | - | 注入条件 |
429
- | templateVars | `Record<string, string>` | - | 规则级模板变量(覆盖全局) |
430
- | allowScriptInjection | `boolean` | `false` | 是否允许注入脚本等危险内容 |
431
-
432
- **InjectCondition**
433
-
434
- | 属性 | 类型 | 默认值 | 描述 |
435
- | ------ | ------------------------------------------- | ------- | ------------------ |
436
- | type | `'env'` \| `'file-contains'` \| `'custom'` | - | 条件类型(必填) |
437
- | value | `string` \| `((...args: any[]) => boolean)` | - | 条件值(必填) |
438
- | negate | `boolean` | `false` | 是否对条件结果取反 |
337
+ | 属性 | 类型 | 默认值 | 描述 |
338
+ | -------------------- | ------------------------ | ---------- | --------------------------------- |
339
+ | id | `string` | - | 规则唯一标识符 |
340
+ | content | `string` | - | 要注入的 HTML 内容 |
341
+ | position | `InjectPosition` | - | 注入位置 |
342
+ | selector | `string` | - | 选择器(selector 相关位置时必填) |
343
+ | selectorMatch | `'string'` \| `'regex'` | `'string'` | 选择器匹配模式 |
344
+ | priority | `number` | `100` | 规则优先级,数值越小越先执行 |
345
+ | condition | `InjectCondition` | - | 注入条件 |
346
+ | templateVars | `Record<string, string>` | - | 规则级模板变量,覆盖全局变量 |
347
+ | allowScriptInjection | `boolean` | `false` | 是否允许注入脚本等危险内容 |
439
348
 
440
349
  **SecurityConfig**
441
350
 
442
351
  | 属性 | 类型 | 默认值 | 描述 |
443
352
  | ------------------------ | ---------- | ------ | -------------------- |
444
- | blockDangerousTags | `boolean` | `true` | 是否阻止危险标签 |
445
- | blockDangerousAttributes | `boolean` | `true` | 是否阻止危险属性 |
353
+ | blockDangerousTags | `boolean` | `true` | 阻止危险标签 |
354
+ | blockDangerousAttributes | `boolean` | `true` | 阻止危险属性 |
446
355
  | allowedTags | `string[]` | - | 允许通过的标签白名单 |
447
356
  | blockedTags | `string[]` | - | 自定义阻止标签列表 |
448
357
  | blockedAttributes | `string[]` | - | 自定义阻止属性列表 |
449
358
 
450
359
  ```typescript
451
- // 基本使用
452
- htmlInject({
453
- rules: [{ id: 'meta-desc', content: '<meta name="description" content="My App">', position: 'head-end' }]
454
- })
455
-
456
- // 条件注入(仅生产环境)
457
360
  htmlInject({
458
361
  rules: [
459
- {
460
- id: 'analytics',
461
- content: '<script src="/analytics.js"></script>',
462
- position: 'body-end',
463
- condition: { type: 'env', value: 'PRODUCTION' },
464
- allowScriptInjection: true
465
- }
362
+ { id: 'meta-description', content: '<meta name="description" content="{{appName}}">', position: 'head-end', templateVars: { appName: 'My Application' } },
363
+ { id: 'analytics', content: '<script src="/analytics.js"></script>', position: 'body-end', condition: { type: 'env', value: 'PRODUCTION' }, allowScriptInjection: true }
466
364
  ]
467
365
  })
468
-
469
- // 模板变量替换
470
- htmlInject({
471
- templateVars: { appName: 'My App', version: '1.0.0' },
472
- rules: [{ id: 'meta', content: '<meta name="description" content="{{appName}}">', position: 'head-end' }]
473
- })
474
-
475
- // 选择器注入
476
- htmlInject({
477
- rules: [{ id: 'replace-title', content: '<title>New Title</title>', position: 'replace-selector', selector: '<title>.*</title>', selectorMatch: 'regex' }]
478
- })
479
-
480
- // 安全配置
481
- htmlInject({
482
- security: { blockDangerousTags: true, allowedTags: ['iframe'] },
483
- rules: [{ id: 'embed', content: '<iframe src="https://example.com"></iframe>', position: 'body-end' }]
484
- })
485
366
  ```
486
367
 
487
- ### faviconManager
488
-
489
- 在 Vite 构建过程中将网站图标链接注入到 HTML 文件的 head 中。支持字符串简写配置。
490
-
491
- | 选项 | 类型 | 默认值 | 描述 |
492
- | ----------- | -------- | ------ | --------------------------- |
493
- | base | `string` | `'/'` | 图标文件的基础路径 |
494
- | url | `string` | - | 图标的完整 URL |
495
- | link | `string` | - | 自定义完整的 link 标签 HTML |
496
- | icons | `Icon[]` | - | 自定义图标数组 |
497
- | copyOptions | `object` | - | 图标文件复制配置 |
368
+ ---
498
369
 
499
- > 优先级:`link` > `url` > `base`。当提供 `link` 时,直接注入自定义 HTML;当提供 `url` 时,使用完整 URL;否则使用 `base + '/favicon.ico'`。
370
+ ### faviconManager
500
371
 
501
- `Icon` 接口定义:
372
+ 管理网站图标(favicon)链接注入到 HTML 文件,支持字符串简写配置和图标文件复制。
502
373
 
503
- | 属性 | 类型 | 必填 | 描述 |
504
- | ----- | -------- | ---- | -------------- |
505
- | rel | `string` | | 图标关系类型 |
506
- | href | `string` | | 图标 URL |
507
- | sizes | `string` | | 图标尺寸 |
508
- | type | `string` | | 图标 MIME 类型 |
374
+ | 选项 | 类型 | 默认值 | 描述 |
375
+ | ----------- | -------- | ------ | ---------------------------------------- |
376
+ | base | `string` | `'/'` | 图标文件基础路径 |
377
+ | url | `string` | - | 图标完整 URL,优先于 base |
378
+ | link | `string` | - | 自定义完整 link 标签 HTML,优先级最高 |
379
+ | icons | `Icon[]` | - | 自定义图标数组,支持多种格式和尺寸 |
380
+ | copyOptions | `object` | - | 图标文件复制配置(sourceDir, targetDir) |
509
381
 
510
- `copyOptions` 接口定义:
382
+ **Icon**
511
383
 
512
- | 属性 | 类型 | 必填 | 默认值 | 描述 |
513
- | --------- | --------- | ---- | ------ | ---------------- |
514
- | sourceDir | `string` | | - | 图标源文件目录 |
515
- | targetDir | `string` | | - | 图标目标目录 |
516
- | overwrite | `boolean` | | `true` | 是否覆盖同名文件 |
517
- | recursive | `boolean` | 否 | `true` | 是否递归复制 |
384
+ | 属性 | 类型 | 描述 |
385
+ | ----- | -------- | -------------- |
386
+ | rel | `string` | 图标关系类型 |
387
+ | href | `string` | 图标 URL |
388
+ | sizes | `string` | 图标尺寸 |
389
+ | type | `string` | 图标 MIME 类型 |
518
390
 
519
391
  ```typescript
520
- // 使用默认配置
521
392
  faviconManager()
522
-
523
- // 字符串简写(设置 base 路径)
524
393
  faviconManager('/assets')
525
-
526
- // 自定义图标数组
527
394
  faviconManager({
528
395
  base: '/assets',
529
396
  icons: [
530
397
  { rel: 'icon', href: '/favicon.svg', type: 'image/svg+xml' },
531
- { rel: 'icon', href: '/favicon-32x32.png', sizes: '32x32', type: 'image/png' },
532
- { rel: 'apple-touch-icon', href: '/apple-touch-icon.png', sizes: '180x180' }
398
+ { rel: 'icon', href: '/favicon-32x32.png', sizes: '32x32', type: 'image/png' }
533
399
  ]
534
400
  })
535
-
536
- // 自定义完整 link 标签
537
- faviconManager({
538
- link: '<link rel="icon" href="/favicon.svg" type="image/svg+xml" />'
539
- })
540
-
541
- // 带文件复制
542
- faviconManager({
543
- base: '/assets',
544
- copyOptions: {
545
- sourceDir: 'src/assets/icons',
546
- targetDir: 'dist/assets/icons'
547
- }
548
- })
401
+ faviconManager({ link: '<link rel="icon" href="/favicon.svg" type="image/svg+xml" />' })
402
+ faviconManager({ base: '/assets', copyOptions: { sourceDir: 'src/assets/icons', targetDir: 'dist/assets/icons' } })
549
403
  ```
550
404
 
405
+ ---
406
+
551
407
  ### loadingManager
552
408
 
553
- 注入全局 Loading 状态管理,支持 XHR/Fetch 请求拦截、白屏 Loading、自定义样式和生命周期回调。
554
-
555
- **注入策略:**
556
-
557
- - `defaultVisible: false`(默认):所有代码(CSS + HTML + JS)通过 JS 动态注入到 `</body>` 前
558
- - `defaultVisible: true`:CSS + HTML 以静态标签注入到 `</head>` 前(白屏即可见),JS 注入到 `</body>` 前
559
-
560
- | 选项 | 类型 | 默认值 | 描述 |
561
- | -------------- | ----------------------------------------------- | ----------------------- | -------------------------------------------- |
562
- | position | `'center'` \| `'top'` \| `'bottom'` | `'center'` | Loading 显示位置 |
563
- | defaultText | `string` | `'加载中...'` | 默认显示文本 |
564
- | spinnerType | `'spinner'` \| `'dots'` \| `'pulse'` \| `'bar'` | `'spinner'` | 旋转图标类型 |
565
- | style | `LoadingStyle` | - | 自定义样式配置 |
566
- | transition | `TransitionConfig` | `{ enabled: true }` | 过渡动画配置 |
567
- | minDisplayTime | `MinDisplayTime` | `{ enabled: true }` | 最小显示时间配置 |
568
- | delayShow | `DelayShow` | `{ enabled: true }` | 延迟显示配置 |
569
- | debounceHide | `DebounceHide` | `{ enabled: false }` | 防抖隐藏配置 |
570
- | autoBind | `'fetch'` \| `'xhr'` \| `'all'` \| `'none'` | `'none'` | 自动绑定请求拦截模式 |
571
- | requestFilter | `RequestFilter` | - | 请求过滤配置 |
572
- | globalName | `string` | `'__LOADING_MANAGER__'` | 注入到浏览器的全局变量名 |
573
- | customTemplate | `string` | - | 自定义 HTML 模板(需含 `data-loading-text`) |
574
- | defaultVisible | `boolean` | `false` | 初始是否可见(白屏 Loading) |
575
- | autoHideOn | `'DOMContentLoaded'` \| `'load'` \| `'manual'` | `'DOMContentLoaded'` | 自动隐藏时机(需 `defaultVisible: true`) |
576
- | callbacks | `LoadingCallbacks` | - | 生命周期回调 |
409
+ 全局 Loading 状态管理,支持请求拦截和白屏 Loading
410
+
411
+ | 选项 | 类型 | 默认值 | 描述 |
412
+ | -------------- | ----------------------------------------------- | ----------------------- | ------------------------ |
413
+ | position | `'center'` \| `'top'` \| `'bottom'` | `'center'` | Loading 显示位置 |
414
+ | defaultText | `string` | `'加载中...'` | 默认显示文本 |
415
+ | spinnerType | `'spinner'` \| `'dots'` \| `'pulse'` \| `'bar'` | `'spinner'` | 旋转图标类型 |
416
+ | autoBind | `'fetch'` \| `'xhr'` \| `'all'` \| `'none'` | `'none'` | 自动绑定请求拦截模式 |
417
+ | globalName | `string` | `'__LOADING_MANAGER__'` | 注入到浏览器的全局变量名 |
418
+ | defaultVisible | `boolean` | `false` | Loading DOM 初始可见状态 |
419
+ | autoHideOn | `'DOMContentLoaded'` \| `'load'` \| `'manual'` | `'DOMContentLoaded'` | 自动隐藏时机 |
420
+ | style | `LoadingStyle` | - | 自定义样式配置 |
421
+ | transition | `TransitionConfig` | - | 过渡动画配置 |
422
+ | minDisplayTime | `MinDisplayTime` | - | 最小显示时间配置 |
423
+ | delayShow | `DelayShow` | - | 延迟显示配置 |
424
+ | debounceHide | `DebounceHide` | - | 防抖隐藏配置 |
425
+ | requestFilter | `RequestFilter` | - | 请求过滤配置 |
426
+ | customTemplate | `string` | - | 自定义 HTML 模板 |
427
+ | callbacks | `LoadingCallbacks` | - | 生命周期回调 |
577
428
 
578
429
  **LoadingStyle**
579
430
 
@@ -584,388 +435,148 @@ faviconManager({
584
435
  | spinnerSize | `string` | `'40px'` | 图标大小 |
585
436
  | textColor | `string` | `'#333'` | 文本颜色 |
586
437
  | textSize | `string` | `'14px'` | 文本大小 |
587
- | customClass | `string` | - | 自定义 CSS 类名 |
588
- | customStyle | `string` | - | 自定义内联样式 |
589
438
  | zIndex | `number` | `9999` | z-index 值 |
590
439
  | pointerEvents | `boolean` | `true` | 是否启用遮罩层指针事件 |
591
440
  | backdropBlur | `boolean` | `false` | 是否启用背景模糊 |
592
441
  | backdropBlurAmount | `number` | `4` | 背景模糊程度(px) |
442
+ | customClass | `string` | - | 自定义 CSS 类名 |
443
+ | customStyle | `string` | - | 自定义内联样式字符串 |
593
444
 
594
- **TransitionConfig**
595
-
596
- | 属性 | 类型 | 默认值 | 描述 |
597
- | -------- | --------- | ------------ | ---------------- |
598
- | enabled | `boolean` | `true` | 是否启用过渡 |
599
- | duration | `number` | `200` | 过渡持续时间(ms) |
600
- | easing | `string` | `'ease-out'` | 缓动函数 |
601
-
602
- **MinDisplayTime**
603
-
604
- | 属性 | 类型 | 默认值 | 描述 |
605
- | -------- | --------- | ------ | ------------------------------------- |
606
- | enabled | `boolean` | `true` | 是否启用 |
607
- | duration | `number` | `300` | 最小显示时间(ms),确保 Loading 不闪烁 |
608
-
609
- **DelayShow**
610
-
611
- | 属性 | 类型 | 默认值 | 描述 |
612
- | -------- | --------- | ------ | ---------------------------------------- |
613
- | enabled | `boolean` | `true` | 是否启用 |
614
- | duration | `number` | `200` | 延迟时间(ms),请求在此时间内完成则不显示 |
615
-
616
- **DebounceHide**
617
-
618
- | 属性 | 类型 | 默认值 | 描述 |
619
- | -------- | --------- | ------- | ---------------- |
620
- | enabled | `boolean` | `false` | 是否启用 |
621
- | duration | `number` | `100` | 防抖等待时间(ms) |
622
-
623
- **RequestFilter**
624
-
625
- | 属性 | 类型 | 描述 |
626
- | ------------------ | ---------- | ----------------------------------------- |
627
- | excludeUrls | `RegExp[]` | 排除的 URL 正则数组 |
628
- | includeUrls | `RegExp[]` | 包含的 URL 正则数组(优先级高于 exclude) |
629
- | excludeMethods | `string[]` | 排除的 HTTP 方法数组 |
630
- | excludeUrlPrefixes | `string[]` | 排除的 URL 前缀数组(前缀匹配,更高效) |
631
-
632
- **LoadingCallbacks**
633
-
634
- 回调以**函数体字符串**形式提供(构建时注入到浏览器端,无法传递函数引用)。
635
-
636
- | 属性 | 类型 | 描述 |
637
- | ------------ | -------- | --------------------------------- |
638
- | onBeforeShow | `string` | 显示前回调,`return false` 可阻止 |
639
- | onShow | `string` | 显示后回调 |
640
- | onBeforeHide | `string` | 隐藏前回调,`return false` 可阻止 |
641
- | onHide | `string` | 隐藏后回调 |
642
- | onDestroy | `string` | 销毁时回调 |
643
-
644
- **LoadingManager API**
645
-
646
- 通过 `window.__LOADING_MANAGER__` 访问:
647
-
648
- | 方法 | 说明 |
649
- | -------------------------- | ------------------------------------------ |
650
- | `show(text?)` | 显示 Loading,可传入文本 |
651
- | `hide()` | 隐藏 Loading(受最小显示时间和防抖约束) |
652
- | `forceHide()` | 强制隐藏,忽略最小显示时间和防抖 |
653
- | `toggle(text?)` | 切换 Loading 显示/隐藏状态 |
654
- | `updateText(text)` | 更新文本内容 |
655
- | `isVisible()` | 获取当前是否显示 |
656
- | `isPointerEventsEnabled()` | 获取当前是否启用了指针事件 |
657
- | `enablePointerEvents()` | 启用遮罩层指针事件,拦截所有点击和滚动操作 |
658
- | `disablePointerEvents()` | 禁用遮罩层指针事件,允许交互穿透 |
659
- | `togglePointerEvents()` | 切换遮罩层指针事件状态 |
660
- | `getPendingCount()` | 获取当前挂起的请求数量 |
661
- | `destroy()` | 销毁实例,清理 DOM 并恢复原始拦截器 |
445
+ **运行时 API:**
662
446
 
663
447
  ```typescript
664
- // 白屏 Loading:页面加载即显示,DOM 就绪后自动隐藏
665
- loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
666
-
667
- // 白屏 Loading:所有资源加载完成后隐藏
668
- loadingManager({ defaultVisible: true, autoHideOn: 'load' })
669
-
670
- // Vue/React SPA:白屏即显示,框架渲染完成后手动隐藏
671
- loadingManager({ defaultVisible: true, autoHideOn: 'manual' })
672
- // 在应用入口处:window.__LOADING_MANAGER__.hide()
673
-
674
- // 自动拦截所有请求
675
- loadingManager({ autoBind: 'all' })
676
-
677
- // 自定义样式 + 请求过滤
678
- loadingManager({
679
- style: { overlayColor: 'rgba(0,0,0,0.5)', spinnerColor: '#fff', backdropBlur: true },
680
- autoBind: 'fetch',
681
- requestFilter: { excludeUrls: [/\/api\/health/], excludeUrlPrefixes: ['http://localhost'] }
682
- })
683
-
684
- // 防抖隐藏(避免快速闪烁)
685
- loadingManager({ debounceHide: { enabled: true, duration: 100 } })
686
-
687
- // 生命周期回调
688
- loadingManager({
689
- callbacks: {
690
- onBeforeShow: 'if (shouldSkip) return false;',
691
- onShow: 'console.log("loading shown")',
692
- onBeforeHide: 'if (shouldKeepVisible) return false;',
693
- onHide: 'console.log("loading hidden")'
694
- }
695
- })
696
-
697
- // 手动控制
698
- loadingManager()
699
- window.__LOADING_MANAGER__.show('正在保存...')
448
+ window.__LOADING_MANAGER__.show('加载中...')
700
449
  window.__LOADING_MANAGER__.hide()
450
+ window.__LOADING_MANAGER__.forceHide()
701
451
  window.__LOADING_MANAGER__.toggle()
452
+ window.__LOADING_MANAGER__.updateText('正在处理...')
453
+ window.__LOADING_MANAGER__.isVisible()
454
+ window.__LOADING_MANAGER__.getPendingCount()
455
+ window.__LOADING_MANAGER__.destroy()
456
+ window.__LOADING_MANAGER__.enablePointerEvents()
702
457
  window.__LOADING_MANAGER__.disablePointerEvents()
458
+ window.__LOADING_MANAGER__.togglePointerEvents()
459
+ window.__LOADING_MANAGER__.isPointerEventsEnabled()
703
460
  ```
704
461
 
705
- ## 通用工具函数
706
-
707
- 通过 `@meng-xi/vite-plugin/common` 导出,可在自定义插件中复用:
708
-
709
462
  ```typescript
710
- import { deepMerge, formatDate, parseTemplate, toCamelCase, toPascalCase, stripJsonComments, generateRandomHash, escapeHtmlAttr, Validator } from '@meng-xi/vite-plugin/common'
711
- import { readFileContent, writeFileContent, fileExists, copySourceToTarget } from '@meng-xi/vite-plugin/common/fs'
712
- import { injectBeforeTag, injectHtmlByPriority, injectBeforeTagWithFallback, injectHeadAndBody } from '@meng-xi/vite-plugin/common/html'
713
- import { makeCallback, containsScriptTag, validateIdentifierName } from '@meng-xi/vite-plugin/common/script'
714
- import { validateGlobalName, validateNoScriptInTemplate, validateCallbackFields, validateNonNegativeNumber, validateNestedDuration, validateEnumValue } from '@meng-xi/vite-plugin/common/validation'
463
+ loadingManager()
464
+ loadingManager({ position: 'top', defaultText: '请稍候...' })
465
+ loadingManager({ spinnerType: 'dots' })
466
+ loadingManager({ autoBind: 'fetch', requestFilter: { excludeUrls: [/\/api\/health/], excludeUrlPrefixes: ['http://localhost'] } })
467
+ loadingManager({ style: { overlayColor: 'rgba(0,0,0,0.5)', spinnerColor: '#ff6b6b', backdropBlur: true, backdropBlurAmount: 6 } })
468
+ loadingManager({ transition: { enabled: true, duration: 300, easing: 'cubic-bezier(0.4,0,0.2,1)' } })
469
+ loadingManager({ debounceHide: { enabled: true, duration: 100 } })
470
+ loadingManager({ callbacks: { onShow: 'console.log("loading shown")', onBeforeShow: 'return true', onHide: 'console.log("loading hidden")' } })
471
+ loadingManager({ customTemplate: '<div class="my-loader"><span data-loading-text></span></div>' })
472
+ loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
473
+ loadingManager({ defaultVisible: true, autoHideOn: 'manual' })
715
474
  ```
716
475
 
717
- | 函数 | 说明 | 子路径 |
718
- | ------------------------------- | --------------------------------------------------------------- | ------------------- |
719
- | `deepMerge()` | 深度合并对象(undefined 不覆盖,数组直接覆盖) | `common/object` |
720
- | `formatDate()` | 格式化日期,支持 `{YYYY}`, `{MM}`, `{DD}` 等占位符 | `common/format` |
721
- | `parseTemplate()` | 解析模板字符串,替换占位符 | `common/format` |
722
- | `toCamelCase()` | 转换为驼峰命名(camelCase) | `common/format` |
723
- | `toPascalCase()` | 转换为帕斯卡命名(PascalCase) | `common/format` |
724
- | `stripJsonComments()` | 移除 JSON 字符串中的注释 | `common/format` |
725
- | `generateRandomHash()` | 生成随机哈希字符串(1-64 位) | `common/format` |
726
- | `escapeHtmlAttr()` | 转义 HTML 属性值中的特殊字符,防止 XSS 注入 | `common/format` |
727
- | `readFileContent()` | 异步读取文件内容 | `common/fs` |
728
- | `writeFileContent()` | 异步写入文件内容 | `common/fs` |
729
- | `fileExists()` | 异步检查文件是否存在 | `common/fs` |
730
- | `copySourceToTarget()` | 复制文件或目录,支持增量复制和并发控制 | `common/fs` |
731
- | `injectBeforeTag()` | 在 HTML 指定闭合标签前注入代码 | `common/html` |
732
- | `injectHtmlByPriority()` | 按优先级向 HTML 中注入代码(`</head>` → `</body>` → `</html>`) | `common/html` |
733
- | `injectBeforeTagWithFallback()` | 带回退策略的 HTML 注入(`</body>` → `</html>` → 末尾) | `common/html` |
734
- | `injectHeadAndBody()` | 双区域 HTML 注入(head + body) | `common/html` |
735
- | `makeCallback()` | 将回调函数体包装为安全的函数表达式(含 try-catch) | `common/script` |
736
- | `containsScriptTag()` | 检测字符串是否包含 `<script>` 标签 | `common/script` |
737
- | `validateIdentifierName()` | 验证字符串是否为合法的 JavaScript 标识符,防止原型污染 | `common/script` |
738
- | `validateGlobalName()` | 验证全局变量名的合法性 | `common/validation` |
739
- | `validateNoScriptInTemplate()` | 验证模板字符串不包含 script 标签(XSS 防护) | `common/validation` |
740
- | `validateCallbackFields()` | 验证回调字段不包含 script 标签 | `common/validation` |
741
- | `validateNonNegativeNumber()` | 验证数值为非负数 | `common/validation` |
742
- | `validateNestedDuration()` | 验证嵌套配置项的 duration 合法性 | `common/validation` |
743
- | `validateEnumValue()` | 验证字符串值是否在允许的枚举列表中 | `common/validation` |
476
+ ---
744
477
 
745
478
  ## 插件开发框架
746
479
 
747
- ### BasePlugin 核心概念
748
-
749
- `BasePlugin` 是所有插件的基类,提供了完整的生命周期管理和开发规范:
750
-
751
- #### 生命周期
752
-
753
- | 阶段 | 方法 | 说明 |
754
- | -------- | ------------------ | -------------------------------------- |
755
- | 初始化 | `constructor` | 合并配置、初始化日志和验证器 |
756
- | 配置解析 | `onConfigResolved` | Vite 配置解析完成时调用 |
757
- | 钩子注册 | `addPluginHooks` | 注册 Vite 插件钩子 |
758
- | 销毁 | `destroy` | `closeBundle` 时自动调用,用于清理资源 |
759
-
760
- #### 钩子自动组合
761
-
762
- `toPlugin()` 方法会自动组合以下钩子:
763
-
764
- - **configResolved** - 先执行基类的 `onConfigResolved`,再执行子类注册的钩子
765
- - **closeBundle** - 先执行子类注册的钩子,再执行基类的 `destroy`
766
-
767
- > 子类无需手动注册 `closeBundle` 钩子来清理资源,只需重写 `destroy()` 方法即可。
480
+ ### BasePlugin
768
481
 
769
- #### 必须实现的方法
770
-
771
- | 方法 | 说明 |
772
- | ------------------------ | ------------------ |
773
- | `getPluginName()` | 返回插件名称 |
774
- | `addPluginHooks(plugin)` | 添加 Vite 插件钩子 |
775
-
776
- #### 可选重写的方法
777
-
778
- | 方法 | 默认行为 | 说明 |
779
- | -------------------------- | ----------- | ---------------------------------- |
780
- | `getDefaultOptions()` | 返回 `{}` | 提供插件默认配置 |
781
- | `validateOptions()` | 无验证 | 验证配置参数 |
782
- | `getEnforce()` | `undefined` | 插件执行时机(`'pre'` / `'post'`) |
783
- | `onConfigResolved(config)` | 存储配置 | 配置解析完成回调 |
784
- | `destroy()` | 注销日志 | 插件销毁时的清理逻辑 |
785
-
786
- #### 内置属性
787
-
788
- | 属性 | 类型 | 说明 |
789
- | ------------ | ------------------------ | ----------------- |
790
- | `options` | `Required<T>` | 合并后的完整配置 |
791
- | `logger` | `PluginLogger` | 插件日志记录器 |
792
- | `validator` | `Validator<T>` | 配置验证器 |
793
- | `viteConfig` | `ResolvedConfig \| null` | Vite 解析后的配置 |
794
-
795
- #### 错误处理策略
796
-
797
- 通过 `errorStrategy` 配置项控制错误行为:
798
-
799
- - `'throw'`(默认)- 记录错误并抛出异常,中断构建
800
- - `'log'` - 记录错误但不抛出,继续执行
801
- - `'ignore'` - 记录错误但不抛出,继续执行
802
-
803
- 使用 `safeExecute` / `safeExecuteSync` 包裹可能出错的操作:
482
+ 所有内置插件的基类,提供配置管理、日志记录、生命周期管理和安全执行等核心功能。
804
483
 
805
484
  ```typescript
806
- // 异步安全执行
807
- const result = await this.safeExecute(async () => {
808
- return await someAsyncOperation()
809
- }, '执行异步操作')
810
-
811
- // 同步安全执行
812
- const value = this.safeExecuteSync(() => {
813
- return someSyncOperation()
814
- }, '执行同步操作')
815
- ```
816
-
817
- ### createPluginFactory
818
-
819
- 创建插件工厂函数,支持选项标准化器:
820
-
821
- ```typescript
822
- // 基本使用
823
- const myPlugin = createPluginFactory(MyPlugin)
824
-
825
- // 带标准化器(支持字符串简写配置)
826
- const myPlugin = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { path: opt } : opt))
827
-
828
- // 使用时支持简写
829
- myPlugin('./custom-path')
830
- ```
831
-
832
- ### Validator
833
-
834
- 流畅的配置验证器,支持链式调用:
835
-
836
- ```typescript
837
- import { Validator } from '@meng-xi/vite-plugin/common'
838
-
839
- const validator = new Validator(options)
840
- validator
841
- .field('sourceDir')
842
- .required()
843
- .string()
844
- .field('targetDir')
845
- .required()
846
- .string()
847
- .field('overwrite')
848
- .boolean()
849
- .default(true)
850
- .field('port')
851
- .number()
852
- .field('list')
853
- .array()
854
- .field('config')
855
- .object()
856
- .field('name')
857
- .custom(val => val.length > 0, 'name 不能为空')
858
- .validate()
859
- ```
860
-
861
- | 方法 | 说明 |
862
- | ------------ | -------------------------------------------------- |
863
- | `field()` | 指定要验证的字段 |
864
- | `required()` | 标记字段为必填 |
865
- | `string()` | 验证字段值是否为字符串类型 |
866
- | `boolean()` | 验证字段值是否为布尔类型 |
867
- | `number()` | 验证字段值是否为数字类型 |
868
- | `array()` | 验证字段值是否为数组类型 |
869
- | `object()` | 验证字段值是否为对象类型 |
870
- | `enum()` | 验证字段值是否在允许的枚举列表中 |
871
- | `minValue()` | 验证数字字段值是否不小于指定最小值 |
872
- | `maxValue()` | 验证数字字段值是否不大于指定最大值 |
873
- | `default()` | 为字段设置默认值(仅当值为 undefined/null 时生效) |
874
- | `custom()` | 使用自定义函数验证字段值 |
875
- | `validate()` | 执行验证,失败时抛出错误 |
876
-
877
- ### Logger
878
-
879
- 全局单例日志管理器,为每个插件提供独立的日志控制:
880
-
881
- ```typescript
882
- import { Logger } from '@meng-xi/vite-plugin/logger'
883
-
884
- // 创建日志记录器(通常由 BasePlugin 自动调用)
885
- Logger.create({ name: 'my-plugin', enabled: true })
886
-
887
- // 注销插件日志配置(插件销毁时自动调用)
888
- Logger.unregister('my-plugin')
889
-
890
- // 销毁单例(测试场景使用)
891
- Logger.destroy()
892
- ```
893
-
894
- 日志输出格式:
895
-
896
- ```
897
- ℹ️ [@meng-xi/vite-plugin:my-plugin] Info message
898
- ✅ [@meng-xi/vite-plugin:my-plugin] Success message
899
- ⚠️ [@meng-xi/vite-plugin:my-plugin] Warning message
900
- ❌ [@meng-xi/vite-plugin:my-plugin] Error message
901
- ```
902
-
903
- ### 开发自定义插件示例
904
-
905
- ```typescript
906
- import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
907
- import type { BasePluginOptions, PluginWithInstance } from '@meng-xi/vite-plugin/factory'
485
+ import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
908
486
  import type { Plugin } from 'vite'
909
487
 
910
- interface MyPluginOptions extends BasePluginOptions {
911
- path: string
488
+ interface MyPluginOptions {
489
+ enabled?: boolean
490
+ message?: string
912
491
  }
913
492
 
914
493
  class MyPlugin extends BasePlugin<MyPluginOptions> {
915
- protected getDefaultOptions() {
916
- return { path: './default' }
494
+ protected getPluginName() {
495
+ return 'my-plugin'
917
496
  }
918
-
919
- protected validateOptions(): void {
920
- this.validator.field('path').required().string().validate()
497
+ protected getDefaultOptions() {
498
+ return { enabled: true, message: 'Hello' }
921
499
  }
922
-
923
- protected getPluginName(): string {
924
- return 'my-plugin'
500
+ protected validateOptions() {
501
+ this.validator.field('message').string().validate()
925
502
  }
926
-
927
- protected addPluginHooks(plugin: Plugin): void {
503
+ protected addPluginHooks(plugin: Plugin) {
928
504
  plugin.buildStart = () => {
929
- this.logger.info(`Plugin started with path: ${this.options.path}`)
505
+ this.logger.info(this.options.message)
930
506
  }
931
507
  }
932
-
933
- protected destroy(): void {
934
- super.destroy()
935
- // 自定义清理逻辑,如关闭连接、停止监听等
936
- }
937
508
  }
938
509
 
939
- // 基本使用
940
510
  export const myPlugin = createPluginFactory(MyPlugin)
941
-
942
- // 带标准化器(支持字符串简写配置)
943
- export const myPluginWithNormalizer = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { path: opt } : opt))
944
- // 使用时支持简写:myPluginWithNormalizer('./custom-path')
945
511
  ```
946
512
 
513
+ ### 核心组件
514
+
515
+ | 组件 | 导出路径 | 描述 |
516
+ | --------------------- | ------------------------------ | ---------------------- |
517
+ | `BasePlugin` | `@meng-xi/vite-plugin/factory` | 插件基类 |
518
+ | `createPluginFactory` | `@meng-xi/vite-plugin/factory` | 插件工厂函数创建器 |
519
+ | `PluginWithInstance` | `@meng-xi/vite-plugin/factory` | 带实例引用的插件类型 |
520
+ | `Logger` | `@meng-xi/vite-plugin/logger` | 日志管理器(单例模式) |
521
+ | `Validator` | `@meng-xi/vite-plugin/common` | 流畅 API 配置验证器 |
522
+
523
+ ### 通用工具库
524
+
525
+ | 模块 | 导出路径 | 描述 |
526
+ | ---------- | ---------------------------------------- | -------------------------------------------------- |
527
+ | format | `@meng-xi/vite-plugin/common/format` | 日期格式化、命名转换、模板解析、HTML 转义 |
528
+ | fs | `@meng-xi/vite-plugin/common/fs` | 文件复制、目录遍历、并发控制 |
529
+ | html | `@meng-xi/vite-plugin/common/html` | HTML 注入(injectBeforeTag, injectHeadAndBody 等) |
530
+ | object | `@meng-xi/vite-plugin/common/object` | 深度合并对象 |
531
+ | script | `@meng-xi/vite-plugin/common/script` | 回调包装、script 标签检测、标识符验证 |
532
+ | validation | `@meng-xi/vite-plugin/common/validation` | 全局名校验、XSS 防护、枚举验证等 |
533
+
534
+ ---
535
+
947
536
  ## 子路径导出
948
537
 
949
- 支持按需导入模块,减少打包体积:
538
+ 支持按需导入以减少打包体积:
950
539
 
951
540
  ```typescript
952
- // 完整导入
953
541
  import { buildProgress, copyFile, htmlInject, loadingManager, BasePlugin, Logger } from '@meng-xi/vite-plugin'
954
542
 
955
- // 按模块导入
956
543
  import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
957
544
  import { Logger } from '@meng-xi/vite-plugin/logger'
958
- import { buildProgress, copyFile, generateRouter, htmlInject, loadingManager } from '@meng-xi/vite-plugin/plugins'
959
- import { Validator, readFileContent, writeFileContent } from '@meng-xi/vite-plugin/common'
545
+ import { buildProgress, compressAssets, copyFile, generateRouter, generateVersion, versionUpdateChecker, htmlInject, faviconManager, loadingManager } from '@meng-xi/vite-plugin/plugins'
546
+ import { Validator, readFileContent, writeFileContent, injectHeadAndBody, deepMerge } from '@meng-xi/vite-plugin/common'
960
547
 
961
- // 类型导入(从子路径按需导入类型定义)
962
548
  import type { PluginWithInstance, PluginFactory, BasePluginOptions } from '@meng-xi/vite-plugin/factory'
963
- import type { BuildProgressOptions, GenerateVersionOptions, VersionUpdateCheckerOptions, HtmlInjectOptions, InjectRule, FaviconManagerOptions, LoadingManagerOptions, Icon } from '@meng-xi/vite-plugin/plugins'
549
+ import type { BuildProgressOptions, CompressAssetsOptions, GenerateVersionOptions, VersionUpdateCheckerOptions, HtmlInjectOptions, FaviconManagerOptions, LoadingManagerOptions } from '@meng-xi/vite-plugin/plugins'
964
550
  import type { DateFormatOptions } from '@meng-xi/vite-plugin/common/format'
965
551
  import type { HtmlInjectResult, DualInjectResult } from '@meng-xi/vite-plugin/common/html'
966
552
  import type { CopyOptions, CopyResult } from '@meng-xi/vite-plugin/common/fs'
967
553
  ```
968
554
 
555
+ **所有可用子路径:**
556
+
557
+ ```
558
+ @meng-xi/vite-plugin
559
+ @meng-xi/vite-plugin/factory
560
+ @meng-xi/vite-plugin/logger
561
+ @meng-xi/vite-plugin/plugins
562
+ @meng-xi/vite-plugin/plugins/build-progress
563
+ @meng-xi/vite-plugin/plugins/compress-assets
564
+ @meng-xi/vite-plugin/plugins/copy-file
565
+ @meng-xi/vite-plugin/plugins/favicon-manager
566
+ @meng-xi/vite-plugin/plugins/generate-router
567
+ @meng-xi/vite-plugin/plugins/generate-version
568
+ @meng-xi/vite-plugin/plugins/html-inject
569
+ @meng-xi/vite-plugin/plugins/loading-manager
570
+ @meng-xi/vite-plugin/plugins/version-update-checker
571
+ @meng-xi/vite-plugin/common
572
+ @meng-xi/vite-plugin/common/format
573
+ @meng-xi/vite-plugin/common/fs
574
+ @meng-xi/vite-plugin/common/html
575
+ @meng-xi/vite-plugin/common/object
576
+ @meng-xi/vite-plugin/common/script
577
+ @meng-xi/vite-plugin/common/validation
578
+ ```
579
+
969
580
  ## 更新日志
970
581
 
971
582
  查看 [GitHub Releases](https://github.com/MengXi-Studio/vite-plugin/releases)