@meng-xi/vite-plugin 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README-en.md +86 -510
  2. package/README.md +83 -506
  3. package/dist/common/compress/index.cjs +1 -0
  4. package/dist/common/compress/index.d.cts +23 -0
  5. package/dist/common/compress/index.d.mts +23 -0
  6. package/dist/common/compress/index.d.ts +23 -0
  7. package/dist/common/compress/index.mjs +1 -0
  8. package/dist/common/format/index.cjs +1 -1
  9. package/dist/common/format/index.d.cts +33 -1
  10. package/dist/common/format/index.d.mts +33 -1
  11. package/dist/common/format/index.d.ts +33 -1
  12. package/dist/common/format/index.mjs +1 -1
  13. package/dist/common/fs/index.cjs +1 -1
  14. package/dist/common/fs/index.d.cts +70 -2
  15. package/dist/common/fs/index.d.mts +70 -2
  16. package/dist/common/fs/index.d.ts +70 -2
  17. package/dist/common/fs/index.mjs +1 -1
  18. package/dist/common/html/index.cjs +2 -2
  19. package/dist/common/html/index.d.cts +268 -19
  20. package/dist/common/html/index.d.mts +268 -19
  21. package/dist/common/html/index.d.ts +268 -19
  22. package/dist/common/html/index.mjs +2 -2
  23. package/dist/common/index.cjs +1 -1
  24. package/dist/common/index.d.cts +8 -3
  25. package/dist/common/index.d.mts +8 -3
  26. package/dist/common/index.d.ts +8 -3
  27. package/dist/common/index.mjs +1 -1
  28. package/dist/common/path/index.cjs +1 -0
  29. package/dist/common/path/index.d.cts +22 -0
  30. package/dist/common/path/index.d.mts +22 -0
  31. package/dist/common/path/index.d.ts +22 -0
  32. package/dist/common/path/index.mjs +1 -0
  33. package/dist/common/ui/index.cjs +1 -0
  34. package/dist/common/ui/index.d.cts +132 -0
  35. package/dist/common/ui/index.d.mts +132 -0
  36. package/dist/common/ui/index.d.ts +132 -0
  37. package/dist/common/ui/index.mjs +1 -0
  38. package/dist/common/validation/index.cjs +1 -1
  39. package/dist/common/validation/index.d.cts +1 -0
  40. package/dist/common/validation/index.d.mts +1 -0
  41. package/dist/common/validation/index.d.ts +1 -0
  42. package/dist/common/validation/index.mjs +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.d.cts +11 -4
  45. package/dist/index.d.mts +11 -4
  46. package/dist/index.d.ts +11 -4
  47. package/dist/index.mjs +1 -1
  48. package/dist/plugins/buildProgress/index.cjs +2 -2
  49. package/dist/plugins/buildProgress/index.mjs +2 -2
  50. package/dist/plugins/bundleAnalyzer/index.cjs +235 -0
  51. package/dist/plugins/bundleAnalyzer/index.d.cts +215 -0
  52. package/dist/plugins/bundleAnalyzer/index.d.mts +215 -0
  53. package/dist/plugins/bundleAnalyzer/index.d.ts +215 -0
  54. package/dist/plugins/bundleAnalyzer/index.mjs +235 -0
  55. package/dist/plugins/compressAssets/index.cjs +1 -1
  56. package/dist/plugins/compressAssets/index.mjs +1 -1
  57. package/dist/plugins/copyFile/index.d.cts +20 -2
  58. package/dist/plugins/copyFile/index.d.mts +20 -2
  59. package/dist/plugins/copyFile/index.d.ts +20 -2
  60. package/dist/plugins/envGuard/index.cjs +67 -0
  61. package/dist/plugins/envGuard/index.d.cts +156 -0
  62. package/dist/plugins/envGuard/index.d.mts +156 -0
  63. package/dist/plugins/envGuard/index.d.ts +156 -0
  64. package/dist/plugins/envGuard/index.mjs +67 -0
  65. package/dist/plugins/faviconManager/index.cjs +1 -1
  66. package/dist/plugins/faviconManager/index.d.cts +43 -5
  67. package/dist/plugins/faviconManager/index.d.mts +43 -5
  68. package/dist/plugins/faviconManager/index.d.ts +43 -5
  69. package/dist/plugins/faviconManager/index.mjs +1 -1
  70. package/dist/plugins/generateRouter/index.cjs +4 -4
  71. package/dist/plugins/generateRouter/index.d.cts +61 -14
  72. package/dist/plugins/generateRouter/index.d.mts +61 -14
  73. package/dist/plugins/generateRouter/index.d.ts +61 -14
  74. package/dist/plugins/generateRouter/index.mjs +1 -1
  75. package/dist/plugins/generateVersion/index.cjs +1 -1
  76. package/dist/plugins/generateVersion/index.d.cts +12 -0
  77. package/dist/plugins/generateVersion/index.d.mts +12 -0
  78. package/dist/plugins/generateVersion/index.d.ts +12 -0
  79. package/dist/plugins/generateVersion/index.mjs +1 -1
  80. package/dist/plugins/htmlInject/index.cjs +1 -7
  81. package/dist/plugins/htmlInject/index.d.cts +49 -194
  82. package/dist/plugins/htmlInject/index.d.mts +49 -194
  83. package/dist/plugins/htmlInject/index.d.ts +49 -194
  84. package/dist/plugins/htmlInject/index.mjs +1 -7
  85. package/dist/plugins/index.cjs +1 -1
  86. package/dist/plugins/index.d.cts +5 -1
  87. package/dist/plugins/index.d.mts +5 -1
  88. package/dist/plugins/index.d.ts +5 -1
  89. package/dist/plugins/index.mjs +1 -1
  90. package/dist/plugins/loadingManager/index.cjs +2 -2
  91. package/dist/plugins/loadingManager/index.mjs +1 -1
  92. package/dist/plugins/versionUpdateChecker/index.cjs +2 -2
  93. package/dist/plugins/versionUpdateChecker/index.mjs +3 -3
  94. package/dist/shared/vite-plugin.BCuhU1au.mjs +7 -0
  95. package/dist/shared/vite-plugin.BrI73DHA.cjs +7 -0
  96. package/dist/shared/vite-plugin.CmtcnItg.d.cts +261 -0
  97. package/dist/shared/vite-plugin.CmtcnItg.d.mts +261 -0
  98. package/dist/shared/vite-plugin.CmtcnItg.d.ts +261 -0
  99. package/dist/shared/vite-plugin.DnFDPjNf.mjs +1 -0
  100. package/dist/shared/vite-plugin.Dumot0up.mjs +1 -0
  101. package/dist/shared/vite-plugin.FfJ-Wwfu.d.cts +143 -0
  102. package/dist/shared/vite-plugin.FfJ-Wwfu.d.mts +143 -0
  103. package/dist/shared/vite-plugin.FfJ-Wwfu.d.ts +143 -0
  104. package/dist/shared/vite-plugin.soT9a-KD.cjs +1 -0
  105. package/dist/shared/vite-plugin.vwox4bU0.cjs +1 -0
  106. package/package.json +26 -1
package/README.md CHANGED
@@ -15,17 +15,13 @@
15
15
 
16
16
  ## 特性
17
17
 
18
- - **开箱即用** - 提供 9 个实用插件,覆盖构建进度展示、构建产物压缩、文件复制、路由生成、版本管理、版本更新检查、HTML 注入、图标注入、全局 Loading 状态管理等常见场景
19
- - **插件开发框架** - 导出 BasePlugin、Logger、Validator 等核心组件,快速构建符合规范的自定义 Vite 插件
20
- - **完整生命周期** - 支持初始化、配置解析、销毁等生命周期管理,自动组合钩子逻辑
21
- - **类型安全** - 完整的 TypeScript 类型定义,配置验证器确保参数正确性
22
- - **灵活配置** - 所有插件支持详细配置,满足多样化场景需求
23
- - **安全执行** - 内置错误处理策略(throw / log / ignore),统一异常管理
18
+ - **开箱即用** - 11 个实用插件,覆盖构建进度、产物分析与压缩、文件复制、环境变量校验、路由生成、版本管理、HTML 注入、图标管理、全局 Loading 等场景
19
+ - **插件开发框架** - 导出 BasePlugin、Logger、Validator 等核心组件,快速构建自定义 Vite 插件
20
+ - **通用工具库** - 内置 Common 工具模块,支持按需子路径导入
21
+ - **类型安全** - 完整 TypeScript 类型定义与配置验证器
24
22
  - **按需导入** - 支持子路径导出,减少打包体积
25
23
 
26
- ## 文档
27
-
28
- 查看完整文档:[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/)**
29
25
 
30
26
  ## 安装
31
27
 
@@ -42,467 +38,76 @@ pnpm add @meng-xi/vite-plugin -D
42
38
 
43
39
  ## 快速开始
44
40
 
45
- ### 使用内置插件
46
-
47
41
  ```typescript
48
42
  import { defineConfig } from 'vite'
49
- import { buildProgress, 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'
50
44
 
51
45
  export default defineConfig({
52
46
  plugins: [
53
47
  buildProgress(),
48
+ bundleAnalyzer({ outputFormat: 'both' }),
54
49
  compressAssets({ algorithm: 'gzip' }),
55
50
  copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' }),
56
- generateRouter({ pagesJsonPath: 'src/pages.json', outputPath: 'src/router.config.ts' }),
51
+ envGuard({ rules: { VITE_API_URL: { type: 'string', required: true } } }),
52
+ generateRouter(),
57
53
  generateVersion({ format: 'datetime', outputType: 'both' }),
58
54
  versionUpdateChecker(),
59
- htmlInject({
60
- rules: [{ id: 'meta-description', content: '<meta name="description" content="My App">', position: 'head-end' }]
61
- }),
55
+ htmlInject({ rules: [{ id: 'meta', content: '<meta name="description" content="My App">', position: 'head-end' }] }),
62
56
  faviconManager('/assets'),
63
57
  loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
64
58
  ]
65
59
  })
66
60
  ```
67
61
 
68
- ### 访问插件实例
69
-
70
- 所有内置插件返回的对象包含 `pluginInstance` 属性,可访问插件内部状态:
71
-
72
- ```typescript
73
- import type { PluginWithInstance } from '@meng-xi/vite-plugin/factory'
74
- import type { GenerateRouterOptions } from '@meng-xi/vite-plugin'
75
-
76
- const routerPlugin = generateRouter({ watch: true }) as PluginWithInstance<GenerateRouterOptions>
77
- console.log(routerPlugin.pluginInstance?.options)
78
- ```
79
-
80
62
  ## 内置插件
81
63
 
82
- | 插件 | 说明 |
83
- | -------------------- | --------------------------------------------------------------- |
84
- | buildProgress | 终端实时构建进度条,支持 bar / spinner / minimal |
85
- | compressAssets | 构建产物压缩,支持 gzip / brotli / both,并发压缩和统计报告 |
86
- | copyFile | 构建完成后复制文件或目录,支持增量复制 |
87
- | generateRouter | 根据 pages.json 自动生成路由配置(uni-app) |
88
- | generateVersion | 自动生成版本号,支持文件输出和全局变量注入 |
89
- | versionUpdateChecker | 运行时版本更新检查,支持多种提示样式和自定义回调 |
90
- | htmlInject | HTML 内容注入,支持多种位置、条件注入、模板变量替换和安全过滤 |
91
- | faviconManager | 管理网站图标(favicon)链接注入到 HTML 文件,支持字符串简写配置 |
92
- | loadingManager | 全局 Loading 状态管理,支持请求拦截和白屏 Loading |
93
-
94
- ---
95
-
96
- ### buildProgress
97
-
98
- 在终端实时显示 Vite 构建进度条,支持三种显示格式。
99
-
100
- **进度计算逻辑:**
101
-
102
- 1. config 阶段(5%)→ resolve 阶段(10%)→ transform 阶段(15%-85%,按模块转换比例)→ bundle 阶段(+10%)→ write 阶段(+5%)→ 完成(100%)
103
- 2. 非 TTY 终端环境(如 CI/CD)自动降级为日志输出模式
104
-
105
- | 选项 | 类型 | 默认值 | 描述 |
106
- | --------------- | ------------------------------------- | ------- | ------------------------------ |
107
- | width | `number` | `30` | 进度条宽度(字符数) |
108
- | format | `'bar'` \| `'spinner'` \| `'minimal'` | `'bar'` | 进度条显示格式 |
109
- | completeChar | `string` | `'█'` | 已完成部分的填充字符 |
110
- | incompleteChar | `string` | `'░'` | 未完成部分的填充字符 |
111
- | clearOnComplete | `boolean` | `true` | 构建完成后是否清除进度条 |
112
- | showModuleName | `boolean` | `true` | 是否显示当前正在处理的模块名称 |
113
- | theme | `ProgressTheme` | - | 自定义颜色主题 |
114
-
115
- **ProgressTheme**
116
-
117
- | 属性 | 类型 | 描述 |
118
- | --------------- | -------------------------- | -------------- |
119
- | completeColor | `(text: string) => string` | 已完成部分颜色 |
120
- | incompleteColor | `(text: string) => string` | 未完成部分颜色 |
121
- | percentageColor | `(text: string) => string` | 百分比数字颜色 |
122
- | phaseColor | `(text: string) => string` | 阶段标签颜色 |
123
- | moduleColor | `(text: string) => string` | 模块名称颜色 |
124
-
125
- ```typescript
126
- buildProgress()
127
- buildProgress({ format: 'spinner' })
128
- buildProgress({ format: 'minimal' })
129
- buildProgress({ width: 40, completeChar: '■', incompleteChar: '□', clearOnComplete: false })
130
- buildProgress({
131
- theme: {
132
- completeColor: t => `\x1b[32m${t}\x1b[39m`,
133
- incompleteColor: t => `\x1b[90m${t}\x1b[39m`,
134
- percentageColor: t => `\x1b[1m${t}\x1b[22m`,
135
- phaseColor: t => `\x1b[36m${t}\x1b[39m`,
136
- moduleColor: t => `\x1b[90m${t}\x1b[39m`
137
- }
138
- })
139
- ```
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
-
170
- ### copyFile
171
-
172
- 在 Vite 构建完成后复制文件或目录到指定位置,执行时机为 `enforce: 'post'`。
173
-
174
- | 选项 | 类型 | 默认值 | 描述 |
175
- | ----------- | --------- | ------ | -------------------- |
176
- | sourceDir | `string` | - | 源目录路径(必填) |
177
- | targetDir | `string` | - | 目标目录路径(必填) |
178
- | overwrite | `boolean` | `true` | 是否覆盖现有文件 |
179
- | recursive | `boolean` | `true` | 是否递归复制子目录 |
180
- | incremental | `boolean` | `true` | 是否启用增量复制 |
181
-
182
- ```typescript
183
- copyFile({ sourceDir: 'src/assets', targetDir: 'dist/assets' })
184
- copyFile({ sourceDir: 'src/static', targetDir: 'dist/static', overwrite: false, incremental: false })
185
- ```
186
-
187
- ---
188
-
189
- ### generateRouter
190
-
191
- 根据 uni-app 项目的 `pages.json` 自动生成路由配置文件。
192
-
193
- | 选项 | 类型 | 默认值 | 描述 |
194
- | -------------------- | --------------------------------------------------------- | ------------------------ | ----------------------------- |
195
- | pagesJsonPath | `string` | `'src/pages.json'` | pages.json 文件路径 |
196
- | outputPath | `string` | `'src/router.config.ts'` | 输出文件路径 |
197
- | outputFormat | `'ts'` \| `'js'` | `'ts'` | 输出文件格式 |
198
- | nameStrategy | `'path'` \| `'camelCase'` \| `'pascalCase'` \| `'custom'` | `'camelCase'` | 路由名称策略 |
199
- | customNameGenerator | `(path: string) => string` | - | 自定义路由名称生成函数 |
200
- | includeSubPackages | `boolean` | `true` | 是否包含子包路由 |
201
- | watch | `boolean` | `true` | 是否监听变化自动重新生成 |
202
- | metaMapping | `Record<string, string>` | - | 页面 style 字段到 meta 的映射 |
203
- | exportTypes | `boolean` | `true` | 是否导出类型定义 |
204
- | preserveRouteChanges | `boolean` | `true` | 是否保留用户对 routes 的修改 |
205
-
206
- > 默认 `metaMapping` 为 `{ navigationBarTitleText: 'title', requireAuth: 'requireAuth' }`。当 `nameStrategy` 为 `'custom'` 时,必须提供 `customNameGenerator`。
207
-
208
- ```typescript
209
- generateRouter()
210
- generateRouter({ pagesJsonPath: 'pages.json' })
211
- generateRouter({ outputFormat: 'js', outputPath: 'src/router.config.js' })
212
- generateRouter({ nameStrategy: 'pascalCase' })
213
- generateRouter({ nameStrategy: 'custom', customNameGenerator: path => `route_${path.replace(/\//g, '_')}` })
214
- generateRouter({ metaMapping: { navigationBarTitleText: 'title', requireAuth: 'requireAuth', customField: 'custom' } })
215
- ```
216
-
217
- ---
218
-
219
- ### generateVersion
220
-
221
- 在 Vite 构建过程中自动生成版本号。
222
-
223
- | 选项 | 类型 | 默认值 | 描述 |
224
- | ------------ | --------------------------------------------------------------------------------- | ------------------- | ------------------------ |
225
- | format | `'timestamp'` \| `'date'` \| `'datetime'` \| `'semver'` \| `'hash'` \| `'custom'` | `'timestamp'` | 版本号格式 |
226
- | customFormat | `string` | - | 自定义格式模板 |
227
- | semverBase | `string` | `'1.0.0'` | 语义化版本基础值 |
228
- | outputType | `'file'` \| `'define'` \| `'both'` | `'file'` | 输出类型 |
229
- | outputFile | `string` | `'version.json'` | 输出文件路径 |
230
- | defineName | `string` | `'__APP_VERSION__'` | 注入的全局变量名 |
231
- | hashLength | `number` | `8` | 哈希长度(1-32) |
232
- | prefix | `string` | - | 版本号前缀 |
233
- | suffix | `string` | - | 版本号后缀 |
234
- | extra | `Record<string, unknown>` | - | 附加信息(仅 JSON 文件) |
235
-
236
- **customFormat 支持的占位符:**
237
-
238
- | 占位符 | 说明 | 示例 |
239
- | ------------- | --------------------------- | --------------- |
240
- | `{YYYY}` | 四位年份 | `2026` |
241
- | `{YY}` | 两位年份 | `26` |
242
- | `{MM}` | 两位月份 | `05` |
243
- | `{DD}` | 两位日期 | `22` |
244
- | `{HH}` | 两位小时(24h) | `15` |
245
- | `{mm}` | 两位分钟 | `30` |
246
- | `{ss}` | 两位秒数 | `00` |
247
- | `{SSS}` | 三位毫秒 | `123` |
248
- | `{timestamp}` | 时间戳(毫秒) | `1779464601000` |
249
- | `{hash}` | 随机哈希 | `a1b2c3d4` |
250
- | `{major}` | 主版本号(需 semverBase) | `1` |
251
- | `{minor}` | 次版本号(需 semverBase) | `0` |
252
- | `{patch}` | 补丁版本号(需 semverBase) | `0` |
253
-
254
- > 当 `format` 为 `'custom'` 时,必须提供 `customFormat`。当 `outputType` 为 `'define'` 或 `'both'` 时,同时注入 `{defineName}_INFO` 全局变量,包含版本号、构建时间、时间戳等完整信息。
255
-
256
- ```typescript
257
- generateVersion()
258
- generateVersion({ format: 'date' })
259
- generateVersion({ format: 'semver', semverBase: '2.0.0', prefix: 'v' })
260
- generateVersion({ format: 'custom', customFormat: '{YYYY}.{MM}.{DD}-{hash}', hashLength: 6 })
261
- generateVersion({ outputType: 'define', defineName: '__VERSION__' })
262
- generateVersion({ outputType: 'both', outputFile: 'build-info.json', defineName: '__BUILD_VERSION__', extra: { environment: 'production' } })
263
- ```
264
-
265
- ---
266
-
267
- ### versionUpdateChecker
268
-
269
- 在运行时定期检查版本号变更,发现新版本时提示用户刷新页面。通常与 `generateVersion` 插件配合使用。
270
-
271
- **工作原理:**
272
-
273
- 1. `generateVersion` 在构建时生成版本号文件(`version.json`)或注入全局变量
274
- 2. `versionUpdateChecker` 在运行时定期请求版本文件,与当前版本对比
275
- 3. 发现版本不一致时,弹出提示引导用户刷新
276
-
277
- | 选项 | 类型 | 默认值 | 描述 |
278
- | ----------------------- | ------------------------------------ | ------------------------------------------ | ------------------------------------ |
279
- | versionSource | `'define'` \| `'file'` \| `'auto'` | `'auto'` | 当前版本号来源 |
280
- | defineName | `string` | `'__APP_VERSION__'` | define 模式下的全局变量名 |
281
- | checkUrl | `string` | `'/version.json'` | 版本检查文件的 URL 路径 |
282
- | checkInterval | `number` | `300000` | 检查间隔时间(毫秒,默认 5 分钟) |
283
- | checkOnVisibilityChange | `boolean` | `true` | 页面可见性变化时是否立即检查 |
284
- | enableInDev | `boolean` | `false` | 是否在开发模式下启用 |
285
- | promptStyle | `'modal'` \| `'banner'` \| `'toast'` | `'modal'` | 更新提示 UI 样式 |
286
- | promptMessage | `string` | `'发现新版本,是否立即刷新获取最新内容?'` | 提示消息文本 |
287
- | refreshButtonText | `string` | `'立即刷新'` | 刷新按钮文本 |
288
- | dismissButtonText | `string` | `'稍后再说'` | 忽略按钮文本 |
289
- | customPromptTemplate | `string` | - | 自定义提示 UI 的 HTML 模板 |
290
- | customStyle | `string` | - | 自定义 CSS 样式字符串 |
291
- | onUpdateAvailable | `string` | - | 发现新版本时的回调(函数体字符串) |
292
- | onRefresh | `string` | - | 用户选择刷新时的回调(函数体字符串) |
293
- | onDismiss | `string` | - | 用户选择忽略时的回调(函数体字符串) |
294
-
295
- > `versionSource` 说明:`'define'` 从全局变量读取,`'file'` 从版本文件读取,`'auto'` 优先使用 define,回退到 file。自定义模板中可使用
296
- > `{{message}}`、`{{currentVersion}}`、`{{newVersion}}`、`{{refreshButton}}`、`{{dismissButton}}` 占位符。回调以函数体字符串形式提供,可用变量:`currentVersion`、`newVersion`。
297
-
298
- ```typescript
299
- generateVersion({ outputType: 'both' })
300
- versionUpdateChecker()
301
- versionUpdateChecker({ versionSource: 'file' })
302
- versionUpdateChecker({ checkInterval: 60000, promptStyle: 'banner' })
303
- versionUpdateChecker({ promptStyle: 'toast' })
304
- versionUpdateChecker({ promptMessage: '系统已更新,建议刷新体验新功能', refreshButtonText: '更新', dismissButtonText: '取消' })
305
- versionUpdateChecker({ onUpdateAvailable: 'console.log("新版本:", newVersion); return true;', onRefresh: 'console.log("用户选择刷新");', onDismiss: 'console.log("用户选择忽略");' })
306
- versionUpdateChecker({ enableInDev: true })
307
- ```
308
-
309
- ---
310
-
311
- ### htmlInject
312
-
313
- 在 Vite 构建过程中根据配置规则将 HTML 内容注入到目标文件中,支持多种注入位置、条件注入、模板变量替换和安全过滤。
314
-
315
- **注入位置:**
316
-
317
- | 位置 | 说明 |
318
- | ------------------ | -------------------------- |
319
- | `head-start` | 注入到 `<head>` 标签开始后 |
320
- | `head-end` | 注入到 `</head>` 标签前 |
321
- | `body-start` | 注入到 `<body>` 标签开始后 |
322
- | `body-end` | 注入到 `</body>` 标签前 |
323
- | `before-selector` | 注入到选择器匹配内容前 |
324
- | `after-selector` | 注入到选择器匹配内容后 |
325
- | `replace-selector` | 替换选择器匹配的内容 |
326
-
327
- | 选项 | 类型 | 默认值 | 描述 |
328
- | ------------ | ------------------------ | -------------- | -------------------------- |
329
- | targetFile | `string` | `'index.html'` | 目标 HTML 文件路径或文件名 |
330
- | rules | `InjectRule[]` | - | 注入规则数组(必填) |
331
- | security | `SecurityConfig` | - | 安全过滤配置 |
332
- | templateVars | `Record<string, string>` | - | 全局模板变量 |
333
- | logInjection | `boolean` | `true` | 是否输出注入日志 |
334
-
335
- **InjectRule**
336
-
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` | 是否允许注入脚本等危险内容 |
348
-
349
- **SecurityConfig**
350
-
351
- | 属性 | 类型 | 默认值 | 描述 |
352
- | ------------------------ | ---------- | ------ | -------------------- |
353
- | blockDangerousTags | `boolean` | `true` | 阻止危险标签 |
354
- | blockDangerousAttributes | `boolean` | `true` | 阻止危险属性 |
355
- | allowedTags | `string[]` | - | 允许通过的标签白名单 |
356
- | blockedTags | `string[]` | - | 自定义阻止标签列表 |
357
- | blockedAttributes | `string[]` | - | 自定义阻止属性列表 |
358
-
359
- ```typescript
360
- htmlInject({
361
- rules: [
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 }
364
- ]
365
- })
366
- ```
367
-
368
- ---
369
-
370
- ### faviconManager
371
-
372
- 管理网站图标(favicon)链接注入到 HTML 文件,支持字符串简写配置和图标文件复制。
373
-
374
- | 选项 | 类型 | 默认值 | 描述 |
375
- | ----------- | -------- | ------ | ---------------------------------------- |
376
- | base | `string` | `'/'` | 图标文件基础路径 |
377
- | url | `string` | - | 图标完整 URL,优先于 base |
378
- | link | `string` | - | 自定义完整 link 标签 HTML,优先级最高 |
379
- | icons | `Icon[]` | - | 自定义图标数组,支持多种格式和尺寸 |
380
- | copyOptions | `object` | - | 图标文件复制配置(sourceDir, targetDir) |
381
-
382
- **Icon**
383
-
384
- | 属性 | 类型 | 描述 |
385
- | ----- | -------- | -------------- |
386
- | rel | `string` | 图标关系类型 |
387
- | href | `string` | 图标 URL |
388
- | sizes | `string` | 图标尺寸 |
389
- | type | `string` | 图标 MIME 类型 |
390
-
391
- ```typescript
392
- faviconManager()
393
- faviconManager('/assets')
394
- faviconManager({
395
- base: '/assets',
396
- icons: [
397
- { rel: 'icon', href: '/favicon.svg', type: 'image/svg+xml' },
398
- { rel: 'icon', href: '/favicon-32x32.png', sizes: '32x32', type: 'image/png' }
399
- ]
400
- })
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' } })
403
- ```
404
-
405
- ---
406
-
407
- ### loadingManager
408
-
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` | - | 生命周期回调 |
428
-
429
- **LoadingStyle**
430
-
431
- | 属性 | 类型 | 默认值 | 描述 |
432
- | ------------------ | --------- | ------------------------- | ---------------------- |
433
- | overlayColor | `string` | `'rgba(255,255,255,0.7)'` | 遮罩层背景色 |
434
- | spinnerColor | `string` | `'#4361ee'` | 图标颜色 |
435
- | spinnerSize | `string` | `'40px'` | 图标大小 |
436
- | textColor | `string` | `'#333'` | 文本颜色 |
437
- | textSize | `string` | `'14px'` | 文本大小 |
438
- | zIndex | `number` | `9999` | z-index 值 |
439
- | pointerEvents | `boolean` | `true` | 是否启用遮罩层指针事件 |
440
- | backdropBlur | `boolean` | `false` | 是否启用背景模糊 |
441
- | backdropBlurAmount | `number` | `4` | 背景模糊程度(px) |
442
- | customClass | `string` | - | 自定义 CSS 类名 |
443
- | customStyle | `string` | - | 自定义内联样式字符串 |
444
-
445
- **运行时 API:**
446
-
447
- ```typescript
448
- window.__LOADING_MANAGER__.show('加载中...')
449
- window.__LOADING_MANAGER__.hide()
450
- window.__LOADING_MANAGER__.forceHide()
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()
457
- window.__LOADING_MANAGER__.disablePointerEvents()
458
- window.__LOADING_MANAGER__.togglePointerEvents()
459
- window.__LOADING_MANAGER__.isPointerEventsEnabled()
460
- ```
461
-
462
- ```typescript
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' })
474
- ```
475
-
476
- ---
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) | 运行时版本更新检查,支持多种提示样式和自定义回调 |
477
77
 
478
78
  ## 插件开发框架
479
79
 
480
- ### BasePlugin
481
-
482
- 所有内置插件的基类,提供配置管理、日志记录、生命周期管理和安全执行等核心功能。
80
+ 本包导出完整的插件开发框架,帮助快速构建符合规范的自定义 Vite 插件。
483
81
 
484
82
  ```typescript
485
- import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
83
+ import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
486
84
  import type { Plugin } from 'vite'
487
85
 
488
86
  interface MyPluginOptions {
489
- enabled?: boolean
490
- message?: string
87
+ prefix?: string
491
88
  }
492
89
 
493
90
  class MyPlugin extends BasePlugin<MyPluginOptions> {
494
91
  protected getPluginName() {
495
92
  return 'my-plugin'
496
93
  }
94
+
497
95
  protected getDefaultOptions() {
498
- return { enabled: true, message: 'Hello' }
96
+ return { prefix: '[app]' }
499
97
  }
98
+
500
99
  protected validateOptions() {
501
- this.validator.field('message').string().validate()
100
+ this.validator.field('prefix').string().notEmpty().validate()
502
101
  }
102
+
503
103
  protected addPluginHooks(plugin: Plugin) {
504
- plugin.buildStart = () => {
505
- this.logger.info(this.options.message)
104
+ plugin.writeBundle = {
105
+ order: 'post',
106
+ handler: async () => {
107
+ await this.safeExecute(async () => {
108
+ this.logger.info('插件执行中...')
109
+ }, '执行自定义逻辑')
110
+ }
506
111
  }
507
112
  }
508
113
  }
@@ -510,86 +115,58 @@ class MyPlugin extends BasePlugin<MyPluginOptions> {
510
115
  export const myPlugin = createPluginFactory(MyPlugin)
511
116
  ```
512
117
 
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
- ### 通用工具库
118
+ **核心 API:**
524
119
 
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 防护、枚举验证等 |
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/) | 链式配置验证器,校验插件配置参数 |
533
126
 
534
- ---
127
+ ## Common 工具模块
535
128
 
536
- ## 子路径导出
537
-
538
- 支持按需导入以减少打包体积:
129
+ 内置通用工具函数库,按功能模块组织,支持子路径按需导入。
539
130
 
540
131
  ```typescript
541
- import { buildProgress, copyFile, htmlInject, loadingManager, BasePlugin, Logger } from '@meng-xi/vite-plugin'
542
-
543
- import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
544
- import { Logger } from '@meng-xi/vite-plugin/logger'
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'
547
-
548
- import type { PluginWithInstance, PluginFactory, BasePluginOptions } from '@meng-xi/vite-plugin/factory'
549
- import type { BuildProgressOptions, CompressAssetsOptions, GenerateVersionOptions, VersionUpdateCheckerOptions, HtmlInjectOptions, FaviconManagerOptions, LoadingManagerOptions } from '@meng-xi/vite-plugin/plugins'
550
- import type { DateFormatOptions } from '@meng-xi/vite-plugin/common/format'
551
- import type { HtmlInjectResult, DualInjectResult } from '@meng-xi/vite-plugin/common/html'
552
- import type { CopyOptions, CopyResult } from '@meng-xi/vite-plugin/common/fs'
553
- ```
132
+ import { formatFileSize } from '@meng-xi/vite-plugin/common/format'
133
+ import { scanDirectory } from '@meng-xi/vite-plugin/common/fs'
134
+ import { calculateGzipSize } from '@meng-xi/vite-plugin/common/compress'
135
+ ```
136
+
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) | 参数验证工具 |
554
148
 
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
-
580
- ## 更新日志
581
-
582
- 查看 [GitHub Releases](https://github.com/MengXi-Studio/vite-plugin/releases)
583
-
584
- ## 贡献指南
585
-
586
- 欢迎贡献代码!请按以下步骤操作:
149
+ ## 子路径导出
587
150
 
588
- 1. Fork 本项目
589
- 2. 创建功能分支:`git checkout -b feature/your-feature`
590
- 3. 提交变更:`git commit -m "feat: your feature description"`
591
- 4. 推送分支:`git push origin feature/your-feature`
592
- 5. 创建 Pull Request
151
+ | 子路径 | 描述 |
152
+ | ----------------------------------------------------- | ------------------------- |
153
+ | `@meng-xi/vite-plugin` | 主入口(所有插件+框架) |
154
+ | `@meng-xi/vite-plugin/factory` | 插件开发框架 |
155
+ | `@meng-xi/vite-plugin/logger` | 日志管理器 |
156
+ | `@meng-xi/vite-plugin/plugins` | 所有插件 |
157
+ | `@meng-xi/vite-plugin/common` | 所有工具函数 |
158
+ | `@meng-xi/vite-plugin/common/*` | 各工具子模块 |
159
+ | `@meng-xi/vite-plugin/plugins/build-progress` | buildProgress 插件 |
160
+ | `@meng-xi/vite-plugin/plugins/bundle-analyzer` | bundleAnalyzer 插件 |
161
+ | `@meng-xi/vite-plugin/plugins/compress-assets` | compressAssets 插件 |
162
+ | `@meng-xi/vite-plugin/plugins/copy-file` | copyFile 插件 |
163
+ | `@meng-xi/vite-plugin/plugins/env-guard` | envGuard 插件 |
164
+ | `@meng-xi/vite-plugin/plugins/favicon-manager` | faviconManager 插件 |
165
+ | `@meng-xi/vite-plugin/plugins/generate-router` | generateRouter 插件 |
166
+ | `@meng-xi/vite-plugin/plugins/generate-version` | generateVersion 插件 |
167
+ | `@meng-xi/vite-plugin/plugins/html-inject` | htmlInject 插件 |
168
+ | `@meng-xi/vite-plugin/plugins/loading-manager` | loadingManager 插件 |
169
+ | `@meng-xi/vite-plugin/plugins/version-update-checker` | versionUpdateChecker 插件 |
593
170
 
594
171
  ## License
595
172