@meng-xi/vite-plugin 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README-en.md +48 -774
  2. package/README.md +45 -769
  3. package/dist/common/html/index.cjs +2 -2
  4. package/dist/common/html/index.d.cts +268 -19
  5. package/dist/common/html/index.d.mts +268 -19
  6. package/dist/common/html/index.d.ts +268 -19
  7. package/dist/common/html/index.mjs +2 -2
  8. package/dist/common/index.cjs +1 -1
  9. package/dist/common/index.d.cts +4 -1
  10. package/dist/common/index.d.mts +4 -1
  11. package/dist/common/index.d.ts +4 -1
  12. package/dist/common/index.mjs +1 -1
  13. package/dist/common/ui/index.cjs +1 -0
  14. package/dist/common/ui/index.d.cts +132 -0
  15. package/dist/common/ui/index.d.mts +132 -0
  16. package/dist/common/ui/index.d.ts +132 -0
  17. package/dist/common/ui/index.mjs +1 -0
  18. package/dist/common/validation/index.cjs +1 -1
  19. package/dist/common/validation/index.d.cts +1 -0
  20. package/dist/common/validation/index.d.mts +1 -0
  21. package/dist/common/validation/index.d.ts +1 -0
  22. package/dist/common/validation/index.mjs +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.d.cts +6 -2
  25. package/dist/index.d.mts +6 -2
  26. package/dist/index.d.ts +6 -2
  27. package/dist/index.mjs +1 -1
  28. package/dist/plugins/buildProgress/index.cjs +2 -2
  29. package/dist/plugins/buildProgress/index.mjs +2 -2
  30. package/dist/plugins/copyFile/index.d.cts +20 -2
  31. package/dist/plugins/copyFile/index.d.mts +20 -2
  32. package/dist/plugins/copyFile/index.d.ts +20 -2
  33. package/dist/plugins/envGuard/index.cjs +67 -0
  34. package/dist/plugins/envGuard/index.d.cts +156 -0
  35. package/dist/plugins/envGuard/index.d.mts +156 -0
  36. package/dist/plugins/envGuard/index.d.ts +156 -0
  37. package/dist/plugins/envGuard/index.mjs +67 -0
  38. package/dist/plugins/faviconManager/index.cjs +1 -1
  39. package/dist/plugins/faviconManager/index.d.cts +43 -5
  40. package/dist/plugins/faviconManager/index.d.mts +43 -5
  41. package/dist/plugins/faviconManager/index.d.ts +43 -5
  42. package/dist/plugins/faviconManager/index.mjs +1 -1
  43. package/dist/plugins/generateRouter/index.d.cts +61 -14
  44. package/dist/plugins/generateRouter/index.d.mts +61 -14
  45. package/dist/plugins/generateRouter/index.d.ts +61 -14
  46. package/dist/plugins/generateVersion/index.d.cts +12 -0
  47. package/dist/plugins/generateVersion/index.d.mts +12 -0
  48. package/dist/plugins/generateVersion/index.d.ts +12 -0
  49. package/dist/plugins/htmlInject/index.cjs +1 -7
  50. package/dist/plugins/htmlInject/index.d.cts +49 -194
  51. package/dist/plugins/htmlInject/index.d.mts +49 -194
  52. package/dist/plugins/htmlInject/index.d.ts +49 -194
  53. package/dist/plugins/htmlInject/index.mjs +1 -7
  54. package/dist/plugins/index.cjs +1 -1
  55. package/dist/plugins/index.d.cts +4 -1
  56. package/dist/plugins/index.d.mts +4 -1
  57. package/dist/plugins/index.d.ts +4 -1
  58. package/dist/plugins/index.mjs +1 -1
  59. package/dist/plugins/loadingManager/index.cjs +2 -2
  60. package/dist/plugins/loadingManager/index.mjs +1 -1
  61. package/dist/plugins/versionUpdateChecker/index.cjs +2 -2
  62. package/dist/plugins/versionUpdateChecker/index.mjs +3 -3
  63. package/dist/shared/vite-plugin.BCuhU1au.mjs +7 -0
  64. package/dist/shared/vite-plugin.BrI73DHA.cjs +7 -0
  65. package/dist/shared/vite-plugin.CmtcnItg.d.cts +261 -0
  66. package/dist/shared/vite-plugin.CmtcnItg.d.mts +261 -0
  67. package/dist/shared/vite-plugin.CmtcnItg.d.ts +261 -0
  68. package/dist/shared/vite-plugin.DnFDPjNf.mjs +1 -0
  69. package/dist/shared/vite-plugin.Dumot0up.mjs +1 -0
  70. package/dist/shared/vite-plugin.FfJ-Wwfu.d.cts +143 -0
  71. package/dist/shared/vite-plugin.FfJ-Wwfu.d.mts +143 -0
  72. package/dist/shared/vite-plugin.FfJ-Wwfu.d.ts +143 -0
  73. package/dist/shared/vite-plugin.soT9a-KD.cjs +1 -0
  74. package/dist/shared/vite-plugin.vwox4bU0.cjs +1 -0
  75. package/package.json +11 -1
package/README.md CHANGED
@@ -15,18 +15,13 @@
15
15
 
16
16
  ## 特性
17
17
 
18
- - **开箱即用** - 提供 10 个实用插件,覆盖构建进度展示、构建产物分析与压缩、文件复制、路由生成、版本管理、版本更新检查、HTML 注入、图标注入、全局 Loading 状态管理等常见场景
19
- - **插件开发框架** - 导出 BasePlugin、Logger、Validator 等核心组件,快速构建符合规范的自定义 Vite 插件
20
- - **通用工具库** - 内置 Common 工具模块,提供格式化、文件系统、压缩、路径处理、HTML 注入、对象操作、脚本生成、参数验证等可复用工具函数
21
- - **完整生命周期** - 支持初始化、配置解析、销毁等生命周期管理,自动组合钩子逻辑
22
- - **类型安全** - 完整的 TypeScript 类型定义,配置验证器确保参数正确性
23
- - **灵活配置** - 所有插件支持详细配置,满足多样化场景需求
24
- - **安全执行** - 内置错误处理策略(throw / log / ignore),统一异常管理
18
+ - **开箱即用** - 11 个实用插件,覆盖构建进度、产物分析与压缩、文件复制、环境变量校验、路由生成、版本管理、HTML 注入、图标管理、全局 Loading 等场景
19
+ - **插件开发框架** - 导出 BasePlugin、Logger、Validator 等核心组件,快速构建自定义 Vite 插件
20
+ - **通用工具库** - 内置 Common 工具模块,支持按需子路径导入
21
+ - **类型安全** - 完整 TypeScript 类型定义与配置验证器
25
22
  - **按需导入** - 支持子路径导出,减少打包体积
26
23
 
27
- ## 文档
28
-
29
- 查看完整文档:[https://mengxi-studio.github.io/vite-plugin/](https://mengxi-studio.github.io/vite-plugin/)
24
+ 📖 **完整文档:[https://mengxi-studio.github.io/vite-plugin/](https://mengxi-studio.github.io/vite-plugin/)**
30
25
 
31
26
  ## 安装
32
27
 
@@ -43,553 +38,46 @@ pnpm add @meng-xi/vite-plugin -D
43
38
 
44
39
  ## 快速开始
45
40
 
46
- ### 使用内置插件
47
-
48
41
  ```typescript
49
42
  import { defineConfig } from 'vite'
50
- import { buildProgress, bundleAnalyzer, compressAssets, copyFile, generateRouter, generateVersion, versionUpdateChecker, htmlInject, faviconManager, loadingManager } from '@meng-xi/vite-plugin'
43
+ import { buildProgress, bundleAnalyzer, compressAssets, copyFile, envGuard, generateRouter, generateVersion, versionUpdateChecker, htmlInject, faviconManager, loadingManager } from '@meng-xi/vite-plugin'
51
44
 
52
45
  export default defineConfig({
53
46
  plugins: [
54
47
  buildProgress(),
55
- bundleAnalyzer({ outputFormat: 'both', sizeThreshold: 200 }),
48
+ bundleAnalyzer({ outputFormat: 'both' }),
56
49
  compressAssets({ algorithm: 'gzip' }),
57
50
  copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' }),
58
- generateRouter({ pagesJsonPath: 'src/pages.json', outputPath: 'src/router.config.ts' }),
51
+ envGuard({ rules: { VITE_API_URL: { type: 'string', required: true } } }),
52
+ generateRouter(),
59
53
  generateVersion({ format: 'datetime', outputType: 'both' }),
60
54
  versionUpdateChecker(),
61
- htmlInject({
62
- rules: [{ id: 'meta-description', content: '<meta name="description" content="My App">', position: 'head-end' }]
63
- }),
55
+ htmlInject({ rules: [{ id: 'meta', content: '<meta name="description" content="My App">', position: 'head-end' }] }),
64
56
  faviconManager('/assets'),
65
57
  loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
66
58
  ]
67
59
  })
68
60
  ```
69
61
 
70
- ### 访问插件实例
71
-
72
- 所有内置插件返回的对象包含 `pluginInstance` 属性,可访问插件内部状态:
73
-
74
- ```typescript
75
- import type { PluginWithInstance } from '@meng-xi/vite-plugin/factory'
76
- import type { GenerateRouterOptions } from '@meng-xi/vite-plugin'
77
-
78
- const routerPlugin = generateRouter({ watch: true }) as PluginWithInstance<GenerateRouterOptions>
79
- console.log(routerPlugin.pluginInstance?.options)
80
- ```
81
-
82
62
  ## 内置插件
83
63
 
84
- | 插件 | 说明 |
85
- | -------------------- | --------------------------------------------------------------------- |
86
- | buildProgress | 终端实时构建进度条,支持 bar / spinner / minimal |
87
- | bundleAnalyzer | 构建产物体积分析,支持 JSON/HTML 报告、gzip 计算、阈值告警和构建对比 |
88
- | compressAssets | 构建产物压缩,支持 gzip / brotli / both,并发压缩和统计报告 |
89
- | copyFile | 构建完成后复制文件或目录,支持增量复制 |
90
- | generateRouter | 根据 pages.json 自动生成路由配置(uni-app) |
91
- | generateVersion | 自动生成版本号,支持文件输出和全局变量注入 |
92
- | versionUpdateChecker | 运行时版本更新检查,支持多种提示样式和自定义回调 |
93
- | htmlInject | HTML 内容注入,支持多种位置、选择器定位、条件注入、模板变量和安全过滤 |
94
- | faviconManager | 管理网站图标链接注入和文件复制,支持字符串简写配置 |
95
- | loadingManager | 全局 Loading 状态管理,支持请求拦截、防抖、过渡动画和白屏 Loading |
96
-
97
- ---
98
-
99
- ### buildProgress
100
-
101
- 在终端实时显示 Vite 构建进度条,支持三种显示格式。
102
-
103
- **进度计算逻辑:**
104
-
105
- 1. config 阶段(5%)→ resolve 阶段(10%)→ transform 阶段(15%-85%,按模块转换比例)→ bundle 阶段(+10%)→ write 阶段(+5%)→ 完成(100%)
106
- 2. 非 TTY 终端环境(如 CI/CD)自动降级为日志输出模式
107
-
108
- | 选项 | 类型 | 默认值 | 描述 |
109
- | --------------- | ------------------------------------- | ------- | ------------------------------ |
110
- | width | `number` | `30` | 进度条宽度(字符数) |
111
- | format | `'bar'` \| `'spinner'` \| `'minimal'` | `'bar'` | 进度条显示格式 |
112
- | completeChar | `string` | `'█'` | 已完成部分的填充字符 |
113
- | incompleteChar | `string` | `'░'` | 未完成部分的填充字符 |
114
- | clearOnComplete | `boolean` | `true` | 构建完成后是否清除进度条 |
115
- | showModuleName | `boolean` | `true` | 是否显示当前正在处理的模块名称 |
116
- | theme | `ProgressTheme` | - | 自定义颜色主题 |
117
-
118
- **ProgressTheme**
119
-
120
- | 属性 | 类型 | 描述 |
121
- | --------------- | -------------------------- | -------------- |
122
- | completeColor | `(text: string) => string` | 已完成部分颜色 |
123
- | incompleteColor | `(text: string) => string` | 未完成部分颜色 |
124
- | percentageColor | `(text: string) => string` | 百分比数字颜色 |
125
- | phaseColor | `(text: string) => string` | 阶段标签颜色 |
126
- | moduleColor | `(text: string) => string` | 模块名称颜色 |
127
-
128
- ```typescript
129
- buildProgress()
130
- buildProgress({ format: 'spinner' })
131
- buildProgress({ format: 'minimal' })
132
- buildProgress({ width: 40, completeChar: '■', incompleteChar: '□', clearOnComplete: false })
133
- buildProgress({
134
- theme: {
135
- completeColor: t => `\x1b[32m${t}\x1b[39m`,
136
- incompleteColor: t => `\x1b[90m${t}\x1b[39m`,
137
- percentageColor: t => `\x1b[1m${t}\x1b[22m`,
138
- phaseColor: t => `\x1b[36m${t}\x1b[39m`,
139
- moduleColor: t => `\x1b[90m${t}\x1b[39m`
140
- }
141
- })
142
- ```
143
-
144
- ---
145
-
146
- ### bundleAnalyzer
147
-
148
- 在 Vite 构建完成后自动分析输出目录中的构建产物,生成体积统计、模块排行、文件类型分布等关键指标,支持 JSON 报告和 HTML 可视化图表。
149
-
150
- **核心功能:**
151
-
152
- - 扫描构建输出目录,分析 chunk、模块和资源文件
153
- - 计算原始大小和 gzip 压缩大小
154
- - 按文件类型统计体积分布
155
- - Top N 大模块排行
156
- - 体积阈值告警(超过阈值 2 倍标记为 critical)
157
- - 与上次构建结果对比,生成差异报告
158
- - HTML 报告支持 treemap / sunburst / list 三种可视化图表
159
-
160
- | 选项 | 类型 | 默认值 | 描述 |
161
- | ------------------ | --------------------------------------- | ------------------- | ---------------------------------------- |
162
- | outputFormat | `'json'` \| `'html'` \| `'both'` | `'json'` | 报告输出格式 |
163
- | outputFile | `string` | `'bundle-analysis'` | 报告输出文件名(不含扩展名) |
164
- | openAnalyzer | `boolean` | `false` | 是否在生成 HTML 报告后自动打开浏览器 |
165
- | sizeThreshold | `number` | `100` | 体积告警阈值(KB) |
166
- | topModules | `number` | `20` | Top N 大模块排行数量 |
167
- | gzipSize | `boolean` | `true` | 是否计算 gzip 大小 |
168
- | excludeNodeModules | `boolean` | `false` | 是否排除 node_modules 中的模块 |
169
- | excludePatterns | `string[]` | `[]` | 需要排除的文件路径模式列表 |
170
- | includeExtensions | `string[]` | `[]` | 需要包含的文件扩展名列表,为空则包含所有 |
171
- | compareWith | `string` \| `null` | `null` | 用于对比的之前分析报告路径 |
172
- | defaultChartType | `'treemap'` \| `'sunburst'` \| `'list'` | `'treemap'` | HTML 报告中图表的默认展示形式 |
173
-
174
- ```typescript
175
- bundleAnalyzer()
176
- bundleAnalyzer({ outputFormat: 'both', openAnalyzer: true })
177
- bundleAnalyzer({ sizeThreshold: 200, topModules: 30, gzipSize: true })
178
- bundleAnalyzer({ compareWith: 'dist/bundle-analysis.json', defaultChartType: 'sunburst' })
179
- bundleAnalyzer({ excludeNodeModules: true, includeExtensions: ['.js', '.css'] })
180
- ```
181
-
182
- ---
183
-
184
- ### compressAssets
185
-
186
- 在 Vite 构建完成后自动压缩输出目录中的文件,支持 gzip 和 brotli 两种压缩算法。
187
-
188
- | 选项 | 类型 | 默认值 | 描述 |
189
- | ------------------ | ---------------------------------- | ----------------------------------------------------------- | ------------------------------ |
190
- | algorithm | `'gzip'` \| `'brotli'` \| `'both'` | `'gzip'` | 压缩算法 |
191
- | threshold | `number` | `1024` | 最小压缩阈值(字节) |
192
- | deleteOriginalFile | `boolean` | `false` | 压缩后是否删除原始文件 |
193
- | includeExtensions | `string[]` | `['.js', '.css', '.html', '.svg', '.json', '.xml', '.txt']` | 需要压缩的文件扩展名 |
194
- | excludeExtensions | `string[]` | `[]` | 需要排除的文件扩展名 |
195
- | excludePaths | `string[]` | `[]` | 需要排除的路径前缀 |
196
- | compressionLevel | `number` | `9` | gzip 压缩级别(1-9) |
197
- | brotliQuality | `number` | `11` | brotli 压缩质量(1-11) |
198
- | reportOutput | `string` \| `false` | `'compress-report.json'` | 压缩报告输出路径,false 不生成 |
199
- | parallelLimit | `number` | `10` | 并发压缩最大文件数 |
200
-
201
- ```typescript
202
- compressAssets()
203
- compressAssets({ algorithm: 'brotli' })
204
- compressAssets({ algorithm: 'both', threshold: 2048, compressionLevel: 9, brotliQuality: 11 })
205
- compressAssets({ deleteOriginalFile: true, reportOutput: 'compress-report.json' })
206
- compressAssets({ includeExtensions: ['.js', '.css'], excludePaths: ['assets/images'], parallelLimit: 5 })
207
- ```
208
-
209
- ---
210
-
211
- ### copyFile
212
-
213
- 在 Vite 构建完成后复制文件或目录到指定位置,执行时机为 `enforce: 'post'`。
214
-
215
- | 选项 | 类型 | 默认值 | 描述 |
216
- | ----------- | --------- | ------ | -------------------- |
217
- | sourceDir | `string` | - | 源目录路径(必填) |
218
- | targetDir | `string` | - | 目标目录路径(必填) |
219
- | overwrite | `boolean` | `true` | 是否覆盖现有文件 |
220
- | recursive | `boolean` | `true` | 是否递归复制子目录 |
221
- | incremental | `boolean` | `true` | 是否启用增量复制 |
222
-
223
- ```typescript
224
- copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' })
225
- copyFile({ sourceDir: 'src/static', targetDir: 'dist/static', overwrite: false, incremental: false })
226
- ```
227
-
228
- ---
229
-
230
- ### generateRouter
231
-
232
- 根据 uni-app 项目的 `pages.json` 自动生成路由配置文件。
233
-
234
- | 选项 | 类型 | 默认值 | 描述 |
235
- | -------------------- | --------------------------------------------------------- | ------------------------ | ----------------------------- |
236
- | pagesJsonPath | `string` | `'src/pages.json'` | pages.json 文件路径 |
237
- | outputPath | `string` | `'src/router.config.ts'` | 输出文件路径 |
238
- | outputFormat | `'ts'` \| `'js'` | `'ts'` | 输出文件格式 |
239
- | nameStrategy | `'path'` \| `'camelCase'` \| `'pascalCase'` \| `'custom'` | `'camelCase'` | 路由名称策略 |
240
- | customNameGenerator | `(path: string) => string` | - | 自定义路由名称生成函数 |
241
- | includeSubPackages | `boolean` | `true` | 是否包含子包路由 |
242
- | watch | `boolean` | `true` | 是否监听变化自动重新生成 |
243
- | metaMapping | `Record<string, string>` | - | 页面 style 字段到 meta 的映射 |
244
- | exportTypes | `boolean` | `true` | 是否导出类型定义 |
245
- | preserveRouteChanges | `boolean` | `true` | 是否保留用户对 routes 的修改 |
246
-
247
- > 默认 `metaMapping` 为 `{ navigationBarTitleText: 'title', requireAuth: 'requireAuth' }`。当 `nameStrategy` 为 `'custom'` 时,必须提供 `customNameGenerator`。
248
-
249
- ```typescript
250
- generateRouter()
251
- generateRouter({ pagesJsonPath: 'pages.json' })
252
- generateRouter({ outputFormat: 'js', outputPath: 'src/router.config.js' })
253
- generateRouter({ nameStrategy: 'pascalCase' })
254
- generateRouter({ nameStrategy: 'custom', customNameGenerator: path => `route_${path.replace(/\//g, '_')}` })
255
- generateRouter({ metaMapping: { navigationBarTitleText: 'title', requireAuth: 'requireAuth', customField: 'custom' } })
256
- ```
257
-
258
- ---
259
-
260
- ### generateVersion
261
-
262
- 在 Vite 构建过程中自动生成版本号。
263
-
264
- | 选项 | 类型 | 默认值 | 描述 |
265
- | ------------ | --------------------------------------------------------------------------------- | ------------------- | ------------------------ |
266
- | format | `'timestamp'` \| `'date'` \| `'datetime'` \| `'semver'` \| `'hash'` \| `'custom'` | `'timestamp'` | 版本号格式 |
267
- | customFormat | `string` | - | 自定义格式模板 |
268
- | semverBase | `string` | `'1.0.0'` | 语义化版本基础值 |
269
- | outputType | `'file'` \| `'define'` \| `'both'` | `'file'` | 输出类型 |
270
- | outputFile | `string` | `'version.json'` | 输出文件路径 |
271
- | defineName | `string` | `'__APP_VERSION__'` | 注入的全局变量名 |
272
- | hashLength | `number` | `8` | 哈希长度(1-32) |
273
- | prefix | `string` | - | 版本号前缀 |
274
- | suffix | `string` | - | 版本号后缀 |
275
- | extra | `Record<string, unknown>` | - | 附加信息(仅 JSON 文件) |
276
-
277
- **customFormat 支持的占位符:**
278
-
279
- | 占位符 | 说明 | 示例 |
280
- | ------------- | --------------------------- | --------------- |
281
- | `{YYYY}` | 四位年份 | `2026` |
282
- | `{YY}` | 两位年份 | `26` |
283
- | `{MM}` | 两位月份 | `05` |
284
- | `{DD}` | 两位日期 | `22` |
285
- | `{HH}` | 两位小时(24h) | `15` |
286
- | `{mm}` | 两位分钟 | `30` |
287
- | `{ss}` | 两位秒数 | `00` |
288
- | `{SSS}` | 三位毫秒 | `123` |
289
- | `{timestamp}` | 时间戳(毫秒) | `1779464601000` |
290
- | `{hash}` | 随机哈希 | `a1b2c3d4` |
291
- | `{major}` | 主版本号(需 semverBase) | `1` |
292
- | `{minor}` | 次版本号(需 semverBase) | `0` |
293
- | `{patch}` | 补丁版本号(需 semverBase) | `0` |
294
-
295
- > 当 `format` 为 `'custom'` 时,必须提供 `customFormat`。当 `outputType` 为 `'define'` 或 `'both'` 时,同时注入 `{defineName}_INFO` 全局变量,包含版本号、构建时间、时间戳等完整信息。
296
-
297
- ```typescript
298
- generateVersion()
299
- generateVersion({ format: 'date' })
300
- generateVersion({ format: 'semver', semverBase: '2.0.0', prefix: 'v' })
301
- generateVersion({ format: 'custom', customFormat: '{YYYY}.{MM}.{DD}-{hash}', hashLength: 6 })
302
- generateVersion({ outputType: 'define', defineName: '__VERSION__' })
303
- generateVersion({ outputType: 'both', outputFile: 'build-info.json', defineName: '__BUILD_VERSION__', extra: { environment: 'production' } })
304
- ```
305
-
306
- ---
307
-
308
- ### versionUpdateChecker
309
-
310
- 在运行时定期检查版本号变更,发现新版本时提示用户刷新页面。通常与 `generateVersion` 插件配合使用。
311
-
312
- **工作原理:**
313
-
314
- 1. `generateVersion` 在构建时生成版本号文件(`version.json`)或注入全局变量
315
- 2. `versionUpdateChecker` 在运行时定期请求版本文件,与当前版本对比
316
- 3. 发现版本不一致时,弹出提示引导用户刷新
317
-
318
- | 选项 | 类型 | 默认值 | 描述 |
319
- | ----------------------- | ------------------------------------ | ------------------------------------------ | ------------------------------------ |
320
- | versionSource | `'define'` \| `'file'` \| `'auto'` | `'auto'` | 当前版本号来源 |
321
- | defineName | `string` | `'__APP_VERSION__'` | define 模式下的全局变量名 |
322
- | checkUrl | `string` | `'/version.json'` | 版本检查文件的 URL 路径 |
323
- | checkInterval | `number` | `300000` | 检查间隔时间(毫秒,默认 5 分钟) |
324
- | checkOnVisibilityChange | `boolean` | `true` | 页面可见性变化时是否立即检查 |
325
- | enableInDev | `boolean` | `false` | 是否在开发模式下启用 |
326
- | promptStyle | `'modal'` \| `'banner'` \| `'toast'` | `'modal'` | 更新提示 UI 样式 |
327
- | promptMessage | `string` | `'发现新版本,是否立即刷新获取最新内容?'` | 提示消息文本 |
328
- | refreshButtonText | `string` | `'立即刷新'` | 刷新按钮文本 |
329
- | dismissButtonText | `string` | `'稍后再说'` | 忽略按钮文本 |
330
- | customPromptTemplate | `string` | - | 自定义提示 UI 的 HTML 模板 |
331
- | customStyle | `string` | - | 自定义 CSS 样式字符串 |
332
- | onUpdateAvailable | `string` | - | 发现新版本时的回调(函数体字符串) |
333
- | onRefresh | `string` | - | 用户选择刷新时的回调(函数体字符串) |
334
- | onDismiss | `string` | - | 用户选择忽略时的回调(函数体字符串) |
335
-
336
- > `versionSource` 说明:`'define'` 从全局变量读取,`'file'` 从版本文件读取,`'auto'` 优先使用 define,回退到 file。自定义模板中可使用
337
- > `{{message}}`、`{{currentVersion}}`、`{{newVersion}}`、`{{refreshButton}}`、`{{dismissButton}}` 占位符。回调以函数体字符串形式提供,可用变量:`currentVersion`、`newVersion`。
338
-
339
- ```typescript
340
- generateVersion({ outputType: 'both' })
341
- versionUpdateChecker()
342
- versionUpdateChecker({ versionSource: 'file' })
343
- versionUpdateChecker({ checkInterval: 60000, promptStyle: 'banner' })
344
- versionUpdateChecker({ promptStyle: 'toast' })
345
- versionUpdateChecker({ promptMessage: '系统已更新,建议刷新体验新功能', refreshButtonText: '更新', dismissButtonText: '取消' })
346
- versionUpdateChecker({ onUpdateAvailable: 'console.log("新版本:", newVersion); return true;', onRefresh: 'console.log("用户选择刷新");', onDismiss: 'console.log("用户选择忽略");' })
347
- versionUpdateChecker({ enableInDev: true })
348
- ```
349
-
350
- ---
351
-
352
- ### htmlInject
353
-
354
- 在 HTML 文件中注入自定义内容,支持多种位置、选择器定位、条件注入、模板变量替换和安全过滤。
355
-
356
- | 选项 | 类型 | 默认值 | 描述 |
357
- | ------------ | ------------------------ | -------------- | -------------------------- |
358
- | targetFile | `string` | `'index.html'` | 目标 HTML 文件路径或文件名 |
359
- | rules | `InjectRule[]` | - | 注入规则列表(必填) |
360
- | security | `SecurityConfig` | - | 安全过滤配置 |
361
- | templateVars | `Record<string, string>` | `{}` | 全局模板变量映射 |
362
- | logInjection | `boolean` | `true` | 是否在控制台输出注入日志 |
363
-
364
- **InjectRule**
365
-
366
- | 属性 | 类型 | 默认值 | 描述 |
367
- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------------------------------- |
368
- | id | `string` | - | 规则唯一标识 |
369
- | content | `string` | - | 注入内容 |
370
- | position | `'head-start'` \| `'head-end'` \| `'body-start'` \| `'body-end'` \| `'before-selector'` \| `'after-selector'` \| `'replace-selector'` | - | 注入位置 |
371
- | selector | `string` | - | 选择器字符串(selector 相关位置时必填) |
372
- | selectorMatch | `'string'` \| `'regex'` | `'string'` | 选择器匹配模式 |
373
- | priority | `number` | `100` | 规则优先级,数值越小越先执行 |
374
- | condition | `InjectCondition` | - | 注入条件 |
375
- | templateVars | `Record<string, string>` | - | 规则级模板变量(覆盖全局 templateVars) |
376
- | allowScriptInjection | `boolean` | `false` | 是否允许注入脚本等危险内容 |
377
-
378
- **InjectCondition**
379
-
380
- | 属性 | 类型 | 默认值 | 描述 |
381
- | ------ | ------------------------------------------ | ------- | ------------------ |
382
- | type | `'env'` \| `'file-contains'` \| `'custom'` | - | 条件类型 |
383
- | value | `string` \| `(...args: any[]) => boolean` | - | 条件值 |
384
- | negate | `boolean` | `false` | 是否对条件结果取反 |
385
-
386
- **SecurityConfig**
387
-
388
- | 属性 | 类型 | 默认值 | 描述 |
389
- | ------------------------ | ---------- | ------ | ------------------------------ |
390
- | blockDangerousTags | `boolean` | `true` | 是否阻止危险标签(script 等) |
391
- | blockDangerousAttributes | `boolean` | `true` | 是否阻止危险属性(onclick 等) |
392
- | allowedTags | `string[]` | - | 允许通过的标签白名单 |
393
- | blockedTags | `string[]` | - | 自定义阻止标签列表 |
394
- | blockedAttributes | `string[]` | - | 自定义阻止属性列表 |
395
-
396
- ```typescript
397
- htmlInject({
398
- rules: [
399
- { id: 'meta-description', content: '<meta name="description" content="My App">', position: 'head-end' },
400
- { id: 'analytics', content: '<script src="https://analytics.example.com/track.js"></script>', position: 'body-end', allowScriptInjection: true },
401
- { id: 'env-var', content: '<script>window.__ENV__ = "{{env}}"</script>', position: 'head-end', templateVars: { env: 'production' }, allowScriptInjection: true },
402
- { id: 'before-app', content: '<div>Before App</div>', position: 'before-selector', selector: '<div id="app">' },
403
- { id: 'prod-only', content: '<meta name="robots" content="noindex">', position: 'head-end', condition: { type: 'env', value: 'PRODUCTION' } }
404
- ]
405
- })
406
- ```
407
-
408
- ---
409
-
410
- ### faviconManager
411
-
412
- 管理网站图标链接注入到 HTML 文件,支持图标文件复制,支持字符串简写配置。
413
-
414
- | 选项 | 类型 | 默认值 | 描述 |
415
- | ----------- | ------------- | ------ | ----------------------------------------- |
416
- | base | `string` | `'/'` | 图标文件的基础路径 |
417
- | url | `string` | - | 图标完整 URL(优先于 base + favicon.ico) |
418
- | link | `string` | - | 自定义完整 link 标签 HTML(最高优先级) |
419
- | icons | `Icon[]` | - | 自定义图标数组,支持多种格式和尺寸 |
420
- | copyOptions | `CopyOptions` | - | 图标文件复制配置 |
421
-
422
- **Icon**
423
-
424
- | 属性 | 类型 | 描述 |
425
- | ----- | -------- | -------------- |
426
- | rel | `string` | 图标关系类型 |
427
- | href | `string` | 图标 URL |
428
- | sizes | `string` | 图标尺寸 |
429
- | type | `string` | 图标 MIME 类型 |
430
-
431
- **CopyOptions**
432
-
433
- | 属性 | 类型 | 默认值 | 描述 |
434
- | --------- | --------- | ------ | ---------------------- |
435
- | sourceDir | `string` | - | 图标源文件目录(必填) |
436
- | targetDir | `string` | - | 图标目标目录(必填) |
437
- | overwrite | `boolean` | `true` | 是否覆盖同名文件 |
438
- | recursive | `boolean` | `true` | 是否递归复制 |
439
-
440
- ```typescript
441
- faviconManager('/assets')
442
- faviconManager({ base: '/assets', url: '/assets/favicon.ico' })
443
- faviconManager({
444
- base: '/assets',
445
- icons: [
446
- { rel: 'icon', href: '/favicon.svg', type: 'image/svg+xml' },
447
- { rel: 'icon', href: '/favicon-32x32.png', sizes: '32x32', type: 'image/png' }
448
- ]
449
- })
450
- faviconManager({
451
- base: '/assets',
452
- copyOptions: { sourceDir: 'src/assets/icons', targetDir: 'dist/assets/icons' }
453
- })
454
- ```
455
-
456
- ---
457
-
458
- ### loadingManager
459
-
460
- 全局 Loading 状态管理,支持请求拦截、防抖、过渡动画和白屏 Loading。
461
-
462
- | 选项 | 类型 | 默认值 | 描述 |
463
- | -------------- | ------------------ | ----------------------- | ------------------------------------------------ |
464
- | position | `LoadingPosition` | `'center'` | Loading 显示位置 |
465
- | defaultText | `string` | `'加载中...'` | 默认显示文本 |
466
- | spinnerType | `SpinnerType` | `'spinner'` | 旋转图标类型 |
467
- | style | `LoadingStyle` | - | 自定义样式配置 |
468
- | transition | `TransitionConfig` | - | 过渡动画配置 |
469
- | minDisplayTime | `MinDisplayTime` | - | 最小显示时间配置 |
470
- | delayShow | `DelayShow` | - | 延迟显示配置 |
471
- | debounceHide | `DebounceHide` | - | 防抖隐藏配置 |
472
- | autoBind | `AutoBindMode` | `'none'` | 自动绑定请求拦截模式 |
473
- | requestFilter | `RequestFilter` | - | 请求过滤配置 |
474
- | globalName | `string` | `'__LOADING_MANAGER__'` | 注入的全局变量名 |
475
- | customTemplate | `string` | - | 自定义 Loading HTML 模板 |
476
- | defaultVisible | `boolean` | `false` | Loading DOM 初始可见状态(白屏 Loading) |
477
- | autoHideOn | `AutoHideOn` | `'DOMContentLoaded'` | 自动隐藏时机(仅 defaultVisible 为 true 时生效) |
478
- | callbacks | `LoadingCallbacks` | - | 生命周期回调 |
479
-
480
- **LoadingPosition**:`'center'` | `'top'` | `'bottom'`
481
-
482
- **SpinnerType**:`'spinner'` | `'dots'` | `'pulse'` | `'bar'`
483
-
484
- **AutoBindMode**:`'fetch'` | `'xhr'` | `'all'` | `'none'`
485
-
486
- **AutoHideOn**:`'DOMContentLoaded'` | `'load'` | `'manual'`
487
-
488
- **LoadingStyle**
489
-
490
- | 属性 | 类型 | 默认值 | 描述 |
491
- | ------------------ | --------- | ------------------------- | ---------------------- |
492
- | overlayColor | `string` | `'rgba(255,255,255,0.7)'` | 遮罩层背景色 |
493
- | spinnerColor | `string` | `'#4361ee'` | Loading 图标颜色 |
494
- | spinnerSize | `string` | `'40px'` | Loading 图标大小 |
495
- | textColor | `string` | `'#333'` | 文本颜色 |
496
- | textSize | `string` | `'14px'` | 文本大小 |
497
- | customClass | `string` | - | 自定义 CSS 类名 |
498
- | customStyle | `string` | - | 自定义内联样式字符串 |
499
- | zIndex | `number` | `9999` | 遮罩层 z-index |
500
- | pointerEvents | `boolean` | `true` | 是否启用遮罩层指针事件 |
501
- | backdropBlur | `boolean` | `false` | 是否启用背景模糊效果 |
502
- | backdropBlurAmount | `number` | `4` | 背景模糊程度(px) |
503
-
504
- **TransitionConfig**
505
-
506
- | 属性 | 类型 | 默认值 | 描述 |
507
- | -------- | --------- | ------------ | ---------------------- |
508
- | enabled | `boolean` | `true` | 是否启用过渡动画 |
509
- | duration | `number` | `200` | 过渡动画持续时间(ms) |
510
- | easing | `string` | `'ease-out'` | CSS 过渡缓动函数 |
511
-
512
- **MinDisplayTime**
513
-
514
- | 属性 | 类型 | 默认值 | 描述 |
515
- | -------- | --------- | ------ | -------------------- |
516
- | enabled | `boolean` | `true` | 是否启用最小显示时间 |
517
- | duration | `number` | `300` | 最小显示时间(ms) |
518
-
519
- **DelayShow**
520
-
521
- | 属性 | 类型 | 默认值 | 描述 |
522
- | -------- | --------- | ------ | ------------------------------------------ |
523
- | enabled | `boolean` | `true` | 是否启用延迟显示 |
524
- | duration | `number` | `200` | 延迟时间(ms),请求在此时间内完成则不显示 |
525
-
526
- **DebounceHide**
527
-
528
- | 属性 | 类型 | 默认值 | 描述 |
529
- | -------- | --------- | ------- | ------------------ |
530
- | enabled | `boolean` | `false` | 是否启用防抖隐藏 |
531
- | duration | `number` | `100` | 防抖等待时间(ms) |
532
-
533
- **RequestFilter**
534
-
535
- | 属性 | 类型 | 描述 |
536
- | ------------------ | ---------- | ----------------------------- |
537
- | excludeUrls | `RegExp[]` | 需要排除的 URL 正则表达式数组 |
538
- | includeUrls | `RegExp[]` | 需要包含的 URL 正则表达式数组 |
539
- | excludeMethods | `string[]` | 需要排除的 HTTP 方法数组 |
540
- | excludeUrlPrefixes | `string[]` | 需要排除的 URL 字符串前缀数组 |
541
-
542
- **LoadingCallbacks**
543
-
544
- | 属性 | 类型 | 描述 |
545
- | ------------ | -------- | --------------------------------------- |
546
- | onBeforeShow | `string` | 显示前回调(`return false` 可阻止显示) |
547
- | onShow | `string` | 显示后回调 |
548
- | onBeforeHide | `string` | 隐藏前回调(`return false` 可阻止隐藏) |
549
- | onHide | `string` | 隐藏后回调 |
550
- | onDestroy | `string` | 销毁时回调 |
551
-
552
- > 回调以函数体字符串形式提供,因为需要注入到客户端代码中。`customTemplate` 中必须包含具有 `data-loading-text` 属性的元素用于文本显示。
553
-
554
- **运行时 API:**
555
-
556
- ```typescript
557
- window.__LOADING_MANAGER__.show('加载中...')
558
- window.__LOADING_MANAGER__.hide()
559
- window.__LOADING_MANAGER__.forceHide()
560
- window.__LOADING_MANAGER__.toggle('正在加载...')
561
- window.__LOADING_MANAGER__.updateText('正在处理...')
562
- window.__LOADING_MANAGER__.isVisible()
563
- window.__LOADING_MANAGER__.getPendingCount()
564
- window.__LOADING_MANAGER__.enablePointerEvents()
565
- window.__LOADING_MANAGER__.disablePointerEvents()
566
- window.__LOADING_MANAGER__.destroy()
567
- ```
568
-
569
- ```typescript
570
- loadingManager()
571
- loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
572
- loadingManager({ position: 'top', defaultText: '请稍候...', spinnerType: 'dots' })
573
- loadingManager({ autoBind: 'fetch', requestFilter: { excludeUrls: [/\/api\/health/] } })
574
- loadingManager({
575
- style: { overlayColor: 'rgba(0,0,0,0.5)', spinnerColor: '#ff6b6b', backdropBlur: true, backdropBlurAmount: 6 }
576
- })
577
- loadingManager({ transition: { enabled: true, duration: 300, easing: 'cubic-bezier(0.4,0,0.2,1)' } })
578
- loadingManager({ debounceHide: { enabled: true, duration: 100 } })
579
- loadingManager({ callbacks: { onShow: 'console.log("shown")', onBeforeShow: 'return true' } })
580
- loadingManager({ customTemplate: '<div class="my-loader"><span data-loading-text></span></div>' })
581
- loadingManager({ defaultVisible: true, autoHideOn: 'manual' })
582
- ```
583
-
584
- ---
64
+ | 插件 | 说明 |
65
+ | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
66
+ | [buildProgress](https://mengxi-studio.github.io/vite-plugin/plugins/build-progress.html) | 终端实时构建进度条,支持 bar / spinner / minimal |
67
+ | [bundleAnalyzer](https://mengxi-studio.github.io/vite-plugin/plugins/bundle-analyzer.html) | 构建产物体积分析,支持 JSON/HTML 报告、gzip 计算、阈值告警和构建对比 |
68
+ | [compressAssets](https://mengxi-studio.github.io/vite-plugin/plugins/compress-assets.html) | 构建产物压缩,支持 gzip / brotli / both,并发压缩和统计报告 |
69
+ | [copyFile](https://mengxi-studio.github.io/vite-plugin/plugins/copy-file.html) | 构建完成后复制文件或目录,支持增量复制 |
70
+ | [envGuard](https://mengxi-studio.github.io/vite-plugin/plugins/) | 环境变量校验,支持类型检查、范围验证、自定义规则和运行时守卫 |
71
+ | [faviconManager](https://mengxi-studio.github.io/vite-plugin/plugins/favicon-manager.html) | 管理网站图标链接注入和文件复制,支持字符串简写配置 |
72
+ | [generateRouter](https://mengxi-studio.github.io/vite-plugin/plugins/generate-router.html) | 根据 pages.json 自动生成路由配置(uni-app) |
73
+ | [generateVersion](https://mengxi-studio.github.io/vite-plugin/plugins/generate-version.html) | 自动生成版本号,支持文件输出和全局变量注入 |
74
+ | [htmlInject](https://mengxi-studio.github.io/vite-plugin/plugins/html-inject.html) | HTML 内容注入,支持多种位置、选择器定位、条件注入、模板变量和安全过滤 |
75
+ | [loadingManager](https://mengxi-studio.github.io/vite-plugin/plugins/loading-manager.html) | 全局 Loading 状态管理,支持请求拦截、防抖、过渡动画和白屏 Loading |
76
+ | [versionUpdateChecker](https://mengxi-studio.github.io/vite-plugin/plugins/version-update-checker.html) | 运行时版本更新检查,支持多种提示样式和自定义回调 |
585
77
 
586
78
  ## 插件开发框架
587
79
 
588
- 本包不仅提供内置插件,还导出完整的插件开发框架,帮助快速构建符合规范的自定义 Vite 插件。
589
-
590
- ### BasePlugin
591
-
592
- 所有内置插件的基类,提供配置管理、日志记录、错误处理和生命周期管理等核心能力。
80
+ 本包导出完整的插件开发框架,帮助快速构建符合规范的自定义 Vite 插件。
593
81
 
594
82
  ```typescript
595
83
  import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
@@ -627,240 +115,36 @@ class MyPlugin extends BasePlugin<MyPluginOptions> {
627
115
  export const myPlugin = createPluginFactory(MyPlugin)
628
116
  ```
629
117
 
630
- **BasePlugin 核心方法:**
631
-
632
- | 方法 | 描述 |
633
- | ------------------- | ------------------------------------------ |
634
- | `getDefaultOptions` | 返回插件默认配置,子类可重写 |
635
- | `validateOptions` | 校验用户配置,子类可重写 |
636
- | `getPluginName` | 返回插件名称(抽象方法,必须实现) |
637
- | `getEnforce` | 返回插件执行时机(pre / post / undefined) |
638
- | `addPluginHooks` | 注册 Vite 钩子(抽象方法,必须实现) |
639
- | `onConfigResolved` | 配置解析完成回调 |
640
- | `destroy` | 插件销毁回调 |
641
- | `safeExecute` | 安全执行异步函数,自动错误处理 |
642
- | `safeExecuteSync` | 安全执行同步函数,自动错误处理 |
643
- | `handleError` | 根据 errorStrategy 处理错误 |
644
- | `toPlugin` | 转换为 Vite 插件对象 |
645
-
646
- **BasePluginOptions 基础配置:**
647
-
648
- | 选项 | 类型 | 默认值 | 描述 |
649
- | ------------- | ---------------------------------- | --------- | ------------ |
650
- | enabled | `boolean` | `true` | 是否启用插件 |
651
- | verbose | `boolean` | `true` | 是否启用日志 |
652
- | errorStrategy | `'throw'` \| `'log'` \| `'ignore'` | `'throw'` | 错误处理策略 |
653
-
654
- ### createPluginFactory
655
-
656
- 创建插件工厂函数,将 BasePlugin 子类转换为可直接使用的 Vite 插件函数。
657
-
658
- ```typescript
659
- import { createPluginFactory } from '@meng-xi/vite-plugin'
660
-
661
- const myPlugin = createPluginFactory(MyPlugin)
662
-
663
- // 支持选项标准化器(如字符串简写配置)
664
- const myPluginWithNormalizer = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { prefix: opt } : opt))
665
- ```
666
-
667
- ### Logger
668
-
669
- 全局单例日志管理器,为每个插件提供独立的日志代理。
670
-
671
- ```typescript
672
- import { Logger } from '@meng-xi/vite-plugin/logger'
673
-
674
- const logger = Logger.create({ name: 'my-plugin', enabled: true })
675
- logger.info('信息日志')
676
- logger.success('成功日志')
677
- logger.warn('警告日志')
678
- logger.error('错误日志')
679
- ```
680
-
681
- ### Validator
118
+ **核心 API:**
682
119
 
683
- 链式配置验证器,用于校验插件配置参数。
684
-
685
- ```typescript
686
- import { Validator } from '@meng-xi/vite-plugin/common/validation'
687
-
688
- const validator = new Validator(myOptions)
689
- validator.field('port').number().minValue(1).maxValue(65535).field('host').string().notEmpty().field('mode').enum(['development', 'production']).validate()
690
- ```
691
-
692
- ---
120
+ | API | 说明 |
121
+ | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
122
+ | [`BasePlugin`](https://mengxi-studio.github.io/vite-plugin/factory/base-plugin.html) | 插件基类,提供配置管理、日志、错误处理和生命周期 |
123
+ | [`createPluginFactory`](https://mengxi-studio.github.io/vite-plugin/factory/create-plugin-factory.html) | 将 BasePlugin 子类转换为 Vite 插件函数 |
124
+ | [`Logger`](https://mengxi-studio.github.io/vite-plugin/logger/) | 全局单例日志管理器,为每个插件提供独立日志代理 |
125
+ | [`Validator`](https://mengxi-studio.github.io/vite-plugin/factory/) | 链式配置验证器,校验插件配置参数 |
693
126
 
694
127
  ## Common 工具模块
695
128
 
696
129
  内置通用工具函数库,按功能模块组织,支持子路径按需导入。
697
130
 
698
- ### 导入方式
699
-
700
131
  ```typescript
701
- // 导入所有工具
702
- import { formatFileSize, scanDirectory } from '@meng-xi/vite-plugin/common'
703
-
704
- // 按模块导入
705
132
  import { formatFileSize } from '@meng-xi/vite-plugin/common/format'
706
- import { scanDirectory, writeJsonReport } from '@meng-xi/vite-plugin/common/fs'
133
+ import { scanDirectory } from '@meng-xi/vite-plugin/common/fs'
707
134
  import { calculateGzipSize } from '@meng-xi/vite-plugin/common/compress'
708
- import { isNodeModule } from '@meng-xi/vite-plugin/common/path'
709
135
  ```
710
136
 
711
- ### 模块列表
712
-
713
- | 子路径 | 描述 |
714
- | ---------------------------------------- | ------------- |
715
- | `@meng-xi/vite-plugin/common/compress` | 压缩算法工具 |
716
- | `@meng-xi/vite-plugin/common/format` | 格式化工具 |
717
- | `@meng-xi/vite-plugin/common/fs` | 文件系统工具 |
718
- | `@meng-xi/vite-plugin/common/html` | HTML 注入工具 |
719
- | `@meng-xi/vite-plugin/common/object` | 对象操作工具 |
720
- | `@meng-xi/vite-plugin/common/path` | 路径处理工具 |
721
- | `@meng-xi/vite-plugin/common/script` | 脚本生成工具 |
722
- | `@meng-xi/vite-plugin/common/validation` | 参数验证工具 |
723
-
724
- ### compress — 压缩算法
725
-
726
- | 函数 | 描述 |
727
- | ------------------- | -------------------------------------- |
728
- | `calculateGzipSize` | 计算给定数据的 gzip 压缩后大小(字节) |
729
-
730
- ```typescript
731
- import { calculateGzipSize } from '@meng-xi/vite-plugin/common/compress'
732
-
733
- const size = await calculateGzipSize(Buffer.from('hello world'))
734
- ```
735
-
736
- ### format — 格式化
737
-
738
- | 函数 | 描述 |
739
- | --------------------- | ---------------------------------------- |
740
- | `formatFileSize` | 将字节数格式化为人类可读的文件大小字符串 |
741
- | `getExtension` | 获取文件扩展名(小写) |
742
- | `formatDate` | 格式化日期 |
743
- | `parseTemplate` | 解析模板字符串,替换占位符 |
744
- | `toCamelCase` | 字符串转驼峰命名 |
745
- | `toPascalCase` | 字符串转帕斯卡命名 |
746
- | `padNumber` | 数字补零格式化 |
747
- | `generateRandomHash` | 生成随机哈希字符串 |
748
- | `getDateFormatParams` | 获取日期格式化参数 |
749
- | `stripJsonComments` | 移除 JSON 字符串中的注释 |
750
- | `escapeHtmlAttr` | 转义 HTML 属性值中的特殊字符 |
751
-
752
- ```typescript
753
- import { formatFileSize, formatDate, toCamelCase } from '@meng-xi/vite-plugin/common/format'
754
-
755
- formatFileSize(2461726) // '2.35MB'
756
- formatDate(new Date(), '{YYYY}-{MM}-{DD}') // '2026-05-31'
757
- toCamelCase('pages/user/profile') // 'pagesUserProfile'
758
- ```
759
-
760
- ### fs — 文件系统
761
-
762
- | 函数 | 描述 |
763
- | -------------------- | -------------------------- |
764
- | `scanDirectory` | 递归扫描目录,收集文件信息 |
765
- | `writeJsonReport` | 将数据写入 JSON 文件 |
766
- | `writeFileContent` | 写入文件内容 |
767
- | `readFileContent` | 读取文件内容 |
768
- | `fileExists` | 检查文件是否存在 |
769
- | `checkSourceExists` | 检查源文件是否存在 |
770
- | `ensureTargetDir` | 创建目标目录 |
771
- | `copySourceToTarget` | 执行文件复制操作 |
772
- | `runWithConcurrency` | 带并发限制的批量执行 |
773
-
774
- ```typescript
775
- import { scanDirectory, writeJsonReport } from '@meng-xi/vite-plugin/common/fs'
776
-
777
- const files = await scanDirectory('dist', {
778
- includeExtensions: ['.js', '.css'],
779
- excludePatterns: ['node_modules'],
780
- filter: (filePath, ext, size) => size > 1024
781
- })
782
-
783
- await writeJsonReport('dist/report.json', { timestamp: Date.now(), files })
784
- ```
785
-
786
- ### html — HTML 注入
787
-
788
- | 函数 | 描述 |
789
- | ----------------------------- | ------------------------------- |
790
- | `injectBeforeTag` | 在指定闭合标签前注入代码 |
791
- | `injectHtmlByPriority` | 按优先级向 HTML 中注入代码 |
792
- | `injectBeforeTagWithFallback` | 带回退策略的 HTML 注入 |
793
- | `injectHeadAndBody` | 双区域 HTML 注入(head + body) |
794
-
795
- ```typescript
796
- import { injectBeforeTag, injectHeadAndBody } from '@meng-xi/vite-plugin/common/html'
797
-
798
- const result = injectBeforeTag(html, '</head>', '<style>body{margin:0}</style>')
799
- const dual = injectHeadAndBody(html, '<style>...</style>', '<script>...</script>')
800
- ```
801
-
802
- ### object — 对象操作
803
-
804
- | 函数 | 描述 |
805
- | ----------- | ------------ |
806
- | `deepMerge` | 深度合并对象 |
807
-
808
- ```typescript
809
- import { deepMerge } from '@meng-xi/vite-plugin/common/object'
810
-
811
- deepMerge({ a: { b: 1 } }, { a: { c: 2 } }) // { a: { b: 1, c: 2 } }
812
- ```
813
-
814
- ### path — 路径处理
815
-
816
- | 函数 | 描述 |
817
- | -------------- | --------------------------------- |
818
- | `isNodeModule` | 判断模块 ID 是否来自 node_modules |
819
-
820
- ```typescript
821
- import { isNodeModule } from '@meng-xi/vite-plugin/common/path'
822
-
823
- isNodeModule('node_modules/lodash/index.js') // true
824
- isNodeModule('src/utils/helper.ts') // false
825
- ```
826
-
827
- ### script — 脚本生成
828
-
829
- | 函数 | 描述 |
830
- | ------------------------ | ---------------------------------------- |
831
- | `makeCallback` | 将回调函数体字符串包装为安全的函数表达式 |
832
- | `containsScriptTag` | 检测字符串是否包含 `<script>` 标签 |
833
- | `validateIdentifierName` | 验证字符串是否为合法的 JS 标识符 |
834
-
835
- ```typescript
836
- import { makeCallback, validateIdentifierName } from '@meng-xi/vite-plugin/common/script'
837
-
838
- makeCallback('console.log("done")')
839
- // 'function() { try { console.log("done") } catch(e) { console.error("[callback] error:", e); } }'
840
-
841
- validateIdentifierName('__APP_VERSION__') // 通过
842
- ```
843
-
844
- ### validation — 参数验证
845
-
846
- | 函数 | 描述 |
847
- | ---------------------------- | -------------------------- |
848
- | `Validator` | 链式配置验证器类 |
849
- | `validateGlobalName` | 验证全局变量名 |
850
- | `validateNoScriptInTemplate` | 验证模板中不含 script 标签 |
851
- | `validateCallbackFields` | 验证回调函数字段 |
852
- | `validateNonNegativeNumber` | 验证非负数 |
853
- | `validateNestedDuration` | 验证嵌套的时长配置 |
854
- | `validateEnumValue` | 验证枚举值 |
855
-
856
- ```typescript
857
- import { Validator } from '@meng-xi/vite-plugin/common/validation'
858
-
859
- const validator = new Validator(options)
860
- validator.field('port').number().minValue(1).maxValue(65535).validate()
861
- ```
862
-
863
- ---
137
+ | 子路径 | 描述 |
138
+ | ----------------------------------------------------------------------------------------- | ------------- |
139
+ | [`common/compress`](https://mengxi-studio.github.io/vite-plugin/common/compress.html) | 压缩算法工具 |
140
+ | [`common/format`](https://mengxi-studio.github.io/vite-plugin/common/format.html) | 格式化工具 |
141
+ | [`common/fs`](https://mengxi-studio.github.io/vite-plugin/common/fs.html) | 文件系统工具 |
142
+ | [`common/html`](https://mengxi-studio.github.io/vite-plugin/common/html.html) | HTML 注入工具 |
143
+ | [`common/object`](https://mengxi-studio.github.io/vite-plugin/common/object.html) | 对象操作工具 |
144
+ | [`common/path`](https://mengxi-studio.github.io/vite-plugin/common/path.html) | 路径处理工具 |
145
+ | [`common/script`](https://mengxi-studio.github.io/vite-plugin/common/script.html) | 脚本生成工具 |
146
+ | [`common/ui`](https://mengxi-studio.github.io/vite-plugin/common/) | 终端 UI 工具 |
147
+ | [`common/validation`](https://mengxi-studio.github.io/vite-plugin/common/validation.html) | 参数验证工具 |
864
148
 
865
149
  ## 子路径导出
866
150
 
@@ -871,18 +155,12 @@ validator.field('port').number().minValue(1).maxValue(65535).validate()
871
155
  | `@meng-xi/vite-plugin/logger` | 日志管理器 |
872
156
  | `@meng-xi/vite-plugin/plugins` | 所有插件 |
873
157
  | `@meng-xi/vite-plugin/common` | 所有工具函数 |
874
- | `@meng-xi/vite-plugin/common/compress` | 压缩工具 |
875
- | `@meng-xi/vite-plugin/common/format` | 格式化工具 |
876
- | `@meng-xi/vite-plugin/common/fs` | 文件系统工具 |
877
- | `@meng-xi/vite-plugin/common/html` | HTML 注入工具 |
878
- | `@meng-xi/vite-plugin/common/object` | 对象操作工具 |
879
- | `@meng-xi/vite-plugin/common/path` | 路径处理工具 |
880
- | `@meng-xi/vite-plugin/common/script` | 脚本生成工具 |
881
- | `@meng-xi/vite-plugin/common/validation` | 参数验证工具 |
158
+ | `@meng-xi/vite-plugin/common/*` | 各工具子模块 |
882
159
  | `@meng-xi/vite-plugin/plugins/build-progress` | buildProgress 插件 |
883
160
  | `@meng-xi/vite-plugin/plugins/bundle-analyzer` | bundleAnalyzer 插件 |
884
161
  | `@meng-xi/vite-plugin/plugins/compress-assets` | compressAssets 插件 |
885
162
  | `@meng-xi/vite-plugin/plugins/copy-file` | copyFile 插件 |
163
+ | `@meng-xi/vite-plugin/plugins/env-guard` | envGuard 插件 |
886
164
  | `@meng-xi/vite-plugin/plugins/favicon-manager` | faviconManager 插件 |
887
165
  | `@meng-xi/vite-plugin/plugins/generate-router` | generateRouter 插件 |
888
166
  | `@meng-xi/vite-plugin/plugins/generate-version` | generateVersion 插件 |
@@ -890,8 +168,6 @@ validator.field('port').number().minValue(1).maxValue(65535).validate()
890
168
  | `@meng-xi/vite-plugin/plugins/loading-manager` | loadingManager 插件 |
891
169
  | `@meng-xi/vite-plugin/plugins/version-update-checker` | versionUpdateChecker 插件 |
892
170
 
893
- ---
894
-
895
171
  ## License
896
172
 
897
173
  [MIT](LICENSE)