fe-stack 0.0.17 → 0.0.18

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fe-stack",
3
- "version": "0.0.17",
3
+ "version": "0.0.18",
4
4
  "description": "共享的配置文件集合,用于 Vite、Tailwind、Biome、Prettier 和 TypeScript",
5
5
  "type": "module",
6
6
  "exports": {
@@ -6,17 +6,13 @@ import Components from 'unplugin-vue-components/vite';
6
6
  import VueRouter from 'unplugin-vue-router/vite';
7
7
  import { defineConfig, mergeConfig } from 'vite';
8
8
  import dts from 'vite-plugin-dts';
9
- import { rollupDtsPlugin } from './vite-plugin-rollup-dts.js';
10
9
 
11
10
  /**
12
11
  * @typedef {import('vite').UserConfig} UserConfig
13
12
  * @typedef {import('vite-plugin-dts').PluginOptions} DtsPluginOptions
14
- * @typedef {Object} RollupDtsOptions
15
- * @property {string} [tsconfigPath] - tsconfig.json 路径
16
- * @property {string} [sharedTypesOutput] - 共享类型输出路径(多入口时)
17
13
  * @typedef {Object} CreateBaseConfigOptions
18
14
  * @property {'app' | 'lib'} [mode] - 构建模式:'app' 为 Vue 应用,'lib' 为库打包
19
- * @property {Partial<DtsPluginOptions> & RollupDtsOptions} [dtsConfig] - vite-plugin-dts 配置(仅 lib 模式),会与默认配置合并
15
+ * @property {Partial<DtsPluginOptions>} [dtsConfig] - vite-plugin-dts 配置(仅 lib 模式),会与默认配置合并
20
16
  * @property {UserConfig} [viteConfig] - 额外的 Vite 配置,会与基础配置合并
21
17
  */
22
18
 
@@ -70,9 +66,6 @@ export function createBaseConfig(dirname, options = {}) {
70
66
 
71
67
  // Lib mode: 提供默认配置
72
68
  if (mode === 'lib') {
73
- // 提取 rollupDts 专用配置
74
- const { sharedTypesOutput, tsconfigPath, ...dtsOnlyConfig } = dtsConfig;
75
-
76
69
  baseConfig.build = {
77
70
  copyPublicDir: false,
78
71
  lib: {
@@ -87,18 +80,10 @@ export function createBaseConfig(dirname, options = {}) {
87
80
  dts({
88
81
  include: ['src/**/*.ts'],
89
82
  root: dirname,
90
- ...dtsOnlyConfig,
91
83
  rollupTypes: false,
84
+ ...dtsConfig,
92
85
  }),
93
86
  );
94
- if (dtsConfig.rollupTypes) {
95
- baseConfig.plugins.push(
96
- rollupDtsPlugin({
97
- tsconfigPath,
98
- sharedTypesOutput,
99
- }),
100
- );
101
- }
102
87
  }
103
88
 
104
89
  // 使用 mergeConfig 合并用户自定义配置
@@ -1,39 +0,0 @@
1
- import type { Plugin } from 'vite';
2
-
3
- /**
4
- * 入口配置
5
- */
6
- export interface Entry {
7
- /** 入口名称 */
8
- name: string;
9
- /** 主入口文件路径 */
10
- mainEntryPoint: string;
11
- /** 输出文件路径 */
12
- output: string;
13
- }
14
-
15
- /**
16
- * Rollup DTS 插件选项
17
- */
18
- export interface RollupDtsPluginOptions {
19
- /** 手动指定入口,如果不指定则从 vite config 的 build.lib.entry 自动获取 */
20
- entries?: Entry[];
21
- /** tsconfig.json 文件路径,默认为 './tsconfig.json' */
22
- tsconfigPath?: string;
23
- /**
24
- * 共享类型输出路径(多入口时使用)
25
- * 插件会自动分析各入口输出,找出在所有入口中都存在的类型声明
26
- * 将这些共享类型提取到指定文件,并更新各入口文件的 import
27
- * @example './dist/shared.d.ts'
28
- */
29
- sharedTypesOutput?: string | null;
30
- }
31
-
32
- /**
33
- * 创建 Vite 插件用于合并 TypeScript 类型声明文件
34
- * @param options - 插件选项
35
- * @returns Vite 插件实例
36
- */
37
- export function rollupDtsPlugin(options?: RollupDtsPluginOptions): Plugin;
38
-
39
- export default rollupDtsPlugin;
@@ -1,477 +0,0 @@
1
- import * as fs from 'node:fs';
2
- import * as path from 'node:path';
3
- import { Extractor, ExtractorConfig } from '@microsoft/api-extractor';
4
-
5
- const baseConfig = {
6
- $schema:
7
- 'https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json',
8
- projectFolder: '.',
9
- apiReport: { enabled: false },
10
- docModel: { enabled: false },
11
- tsdocMetadata: { enabled: false },
12
- dtsRollup: { enabled: true },
13
- messages: {
14
- compilerMessageReporting: { default: { logLevel: 'warning' } },
15
- extractorMessageReporting: {
16
- default: { logLevel: 'warning' },
17
- 'ae-missing-release-tag': { logLevel: 'none' },
18
- 'ae-unresolved-link': { logLevel: 'none' },
19
- },
20
- tsdocMessageReporting: { default: { logLevel: 'none' } },
21
- },
22
- };
23
-
24
- function cleanupIntermediateFiles(dir, keepFiles) {
25
- if (!fs.existsSync(dir)) return;
26
-
27
- const items = fs.readdirSync(dir, { withFileTypes: true });
28
-
29
- for (const item of items) {
30
- const fullPath = path.join(dir, item.name);
31
-
32
- if (item.isDirectory()) {
33
- const hasKeepFile = keepFiles.some(
34
- (f) => f.startsWith(fullPath + path.sep) || f === fullPath,
35
- );
36
- if (hasKeepFile) {
37
- cleanupIntermediateFiles(fullPath, keepFiles);
38
- const remaining = fs.readdirSync(fullPath);
39
- if (remaining.length === 0) {
40
- fs.rmdirSync(fullPath);
41
- }
42
- } else {
43
- const allDts = fs
44
- .readdirSync(fullPath, { recursive: true })
45
- .every((f) => {
46
- if (typeof f !== 'string') return true;
47
- const fp = path.join(fullPath, f);
48
- return fs.statSync(fp).isDirectory() || f.endsWith('.d.ts');
49
- });
50
- if (allDts) {
51
- fs.rmSync(fullPath, { recursive: true });
52
- }
53
- }
54
- } else if (item.name.endsWith('.d.ts') && !keepFiles.includes(fullPath)) {
55
- fs.unlinkSync(fullPath);
56
- }
57
- }
58
- }
59
-
60
- /**
61
- * 从 vite config 的 build.lib.entry 自动生成 entries
62
- */
63
- function getEntriesFromConfig(config) {
64
- const lib = config.build?.lib;
65
- if (!lib) return [];
66
-
67
- const outDir = config.build?.outDir || 'dist';
68
- const entry = lib.entry;
69
-
70
- // entry 可以是 string | string[] | Record<string, string>
71
- if (typeof entry === 'string') {
72
- return [
73
- {
74
- name: 'index',
75
- mainEntryPoint: `./${outDir}/index.d.ts`,
76
- output: `./${outDir}/index.d.ts`,
77
- },
78
- ];
79
- }
80
-
81
- if (Array.isArray(entry)) {
82
- return entry.map((_, i) => ({
83
- name: i === 0 ? 'index' : `entry${i}`,
84
- mainEntryPoint: `./${outDir}/${i === 0 ? 'index' : `entry${i}`}.d.ts`,
85
- output: `./${outDir}/${i === 0 ? 'index' : `entry${i}`}.d.ts`,
86
- }));
87
- }
88
-
89
- // Record<string, string>
90
- return Object.keys(entry).map((name) => ({
91
- name,
92
- mainEntryPoint: `./${outDir}/${name}.d.ts`,
93
- output: `./${outDir}/${name}.d.ts`,
94
- }));
95
- }
96
-
97
- /**
98
- * 使用 API Extractor 处理单个入口
99
- */
100
- function rollupEntry(entry, projectFolder, tsconfigPath) {
101
- const mainEntryPointFilePath = path.resolve(
102
- projectFolder,
103
- entry.mainEntryPoint,
104
- );
105
-
106
- if (!fs.existsSync(mainEntryPointFilePath)) {
107
- console.warn(
108
- `[rollup-dts] ⚠️ Skipping ${entry.name}: ${entry.mainEntryPoint} not found`,
109
- );
110
- return { success: false, skipped: true };
111
- }
112
-
113
- console.log(`[rollup-dts] 📦 Rolling up types for: ${entry.name}`);
114
-
115
- const config = {
116
- ...baseConfig,
117
- compiler: {
118
- tsconfigFilePath: `<projectFolder>/${tsconfigPath}`,
119
- },
120
- mainEntryPointFilePath: `<projectFolder>/${entry.mainEntryPoint}`,
121
- dtsRollup: {
122
- enabled: true,
123
- untrimmedFilePath: `<projectFolder>/${entry.output}`,
124
- },
125
- };
126
-
127
- const safeName = entry.name.replace(/\//g, '-');
128
- const tempConfigPath = path.resolve(
129
- projectFolder,
130
- `api-extractor.${safeName}.tmp.json`,
131
- );
132
- fs.writeFileSync(tempConfigPath, JSON.stringify(config, null, 2));
133
-
134
- let success = false;
135
- try {
136
- const extractorConfig = ExtractorConfig.loadFileAndPrepare(tempConfigPath);
137
- const extractorResult = Extractor.invoke(extractorConfig, {
138
- localBuild: true,
139
- showVerboseMessages: false,
140
- });
141
-
142
- if (extractorResult.succeeded) {
143
- console.log(
144
- `[rollup-dts] ✅ ${entry.name}: types rolled up successfully`,
145
- );
146
- success = true;
147
- } else {
148
- console.warn(
149
- `[rollup-dts] ⚠️ ${entry.name}: API Extractor completed with warnings/errors`,
150
- );
151
- if (fs.existsSync(path.resolve(projectFolder, entry.output))) {
152
- success = true;
153
- }
154
- }
155
- } catch (error) {
156
- console.warn(
157
- `[rollup-dts] ⚠️ ${entry.name}: Error during rollup, keeping original .d.ts files`,
158
- );
159
- console.warn(` ${error instanceof Error ? error.message : error}`);
160
- } finally {
161
- if (fs.existsSync(tempConfigPath)) {
162
- fs.unlinkSync(tempConfigPath);
163
- }
164
- }
165
-
166
- return { success, skipped: false };
167
- }
168
-
169
- /**
170
- * 从 .d.ts 内容中解析类型声明
171
- * 返回 Map<typeName, { declaration: string, kind: string }>
172
- */
173
- function parseTypeDeclarations(content) {
174
- const declarations = new Map();
175
- const lines = content.split('\n');
176
-
177
- let i = 0;
178
- while (i < lines.length) {
179
- const line = lines[i];
180
-
181
- // 匹配类型声明开始
182
- const match = line.match(
183
- /^export\s+declare\s+(interface|type|enum|class|namespace)\s+(\w+)/,
184
- );
185
-
186
- if (match) {
187
- const kind = match[1];
188
- const name = match[2];
189
- const declLines = [line];
190
-
191
- // type alias 可能是单行
192
- if (kind === 'type' && line.includes('=') && line.includes(';')) {
193
- declarations.set(name, { declaration: line, kind });
194
- i++;
195
- continue;
196
- }
197
-
198
- // 多行声明,收集直到闭合
199
- let braceCount =
200
- (line.match(/{/g) || []).length - (line.match(/}/g) || []).length;
201
- i++;
202
-
203
- while (i < lines.length && braceCount > 0) {
204
- declLines.push(lines[i]);
205
- braceCount +=
206
- (lines[i].match(/{/g) || []).length -
207
- (lines[i].match(/}/g) || []).length;
208
- i++;
209
- }
210
-
211
- declarations.set(name, { declaration: declLines.join('\n'), kind });
212
- } else {
213
- i++;
214
- }
215
- }
216
-
217
- return declarations;
218
- }
219
-
220
- /**
221
- * 从多个输出文件中找出共享的类型声明
222
- */
223
- function findSharedTypeDeclarations(outputs) {
224
- if (outputs.length < 2) return new Map();
225
-
226
- // 解析所有文件的类型声明
227
- const allDeclarations = outputs.map((output) => ({
228
- name: output.name,
229
- declarations: parseTypeDeclarations(output.content),
230
- }));
231
-
232
- // 找出在所有文件中都出现的类型名称
233
- const firstDecls = allDeclarations[0].declarations;
234
- const sharedTypes = new Map();
235
-
236
- for (const [typeName, typeInfo] of firstDecls) {
237
- // 检查是否在所有其他文件中都存在
238
- const existsInAll = allDeclarations
239
- .slice(1)
240
- .every((file) => file.declarations.has(typeName));
241
-
242
- if (existsInAll) {
243
- sharedTypes.set(typeName, typeInfo);
244
- }
245
- }
246
-
247
- return sharedTypes;
248
- }
249
-
250
- /**
251
- * 从文件内容中移除指定的类型声明
252
- */
253
- function removeTypeDeclarations(content, typeNames) {
254
- const lines = content.split('\n');
255
- const newLines = [];
256
-
257
- let i = 0;
258
- while (i < lines.length) {
259
- const line = lines[i];
260
-
261
- // 检查是否是要移除的类型声明
262
- const match = line.match(
263
- /^export\s+declare\s+(interface|type|enum|class|namespace)\s+(\w+)/,
264
- );
265
-
266
- if (match && typeNames.includes(match[2])) {
267
- const kind = match[1];
268
-
269
- // type alias 单行
270
- if (kind === 'type' && line.includes('=') && line.includes(';')) {
271
- i++;
272
- continue;
273
- }
274
-
275
- // 多行声明,跳过直到闭合
276
- let braceCount =
277
- (line.match(/{/g) || []).length - (line.match(/}/g) || []).length;
278
- i++;
279
-
280
- while (i < lines.length && braceCount > 0) {
281
- braceCount +=
282
- (lines[i].match(/{/g) || []).length -
283
- (lines[i].match(/}/g) || []).length;
284
- i++;
285
- }
286
- } else {
287
- newLines.push(line);
288
- i++;
289
- }
290
- }
291
-
292
- return newLines.join('\n').replace(/\n{3,}/g, '\n\n').trim();
293
- }
294
-
295
- /**
296
- * 提取共享类型到单独文件,并更新各入口文件
297
- */
298
- function extractSharedTypes(outputs, projectFolder, sharedTypesOutput) {
299
- // 找出共享的类型声明
300
- const sharedTypes = findSharedTypeDeclarations(outputs);
301
-
302
- if (sharedTypes.size === 0) {
303
- console.log('[rollup-dts] ℹ️ No shared types found across entries');
304
- return { sharedTypeNames: [], sharedFilePath: null };
305
- }
306
-
307
- const sharedTypeNames = Array.from(sharedTypes.keys());
308
- console.log(
309
- `[rollup-dts] 📝 Found ${sharedTypes.size} shared types: ${sharedTypeNames.join(', ')}`,
310
- );
311
-
312
- // 生成共享类型文件内容
313
- const sharedContent = Array.from(sharedTypes.values())
314
- .map((t) => t.declaration)
315
- .join('\n\n');
316
-
317
- const sharedFilePath = path.resolve(projectFolder, sharedTypesOutput);
318
-
319
- // 确保目录存在
320
- const sharedDir = path.dirname(sharedFilePath);
321
- if (!fs.existsSync(sharedDir)) {
322
- fs.mkdirSync(sharedDir, { recursive: true });
323
- }
324
-
325
- // 写入共享类型文件
326
- fs.writeFileSync(sharedFilePath, sharedContent + '\n\nexport { }\n', 'utf-8');
327
- console.log(`[rollup-dts] ✅ Shared types written to: ${sharedTypesOutput}`);
328
-
329
- // 更新各入口文件
330
- for (const output of outputs) {
331
- // 移除共享类型声明
332
- let newContent = removeTypeDeclarations(output.content, sharedTypeNames);
333
-
334
- // 找出这个文件中实际使用的共享类型
335
- const usedTypes = sharedTypeNames.filter((name) => {
336
- const regex = new RegExp(`\\b${name}\\b`);
337
- return regex.test(newContent);
338
- });
339
-
340
- if (usedTypes.length > 0) {
341
- // 计算相对路径
342
- const outputDir = path.dirname(output.path);
343
- let relativePath = path
344
- .relative(outputDir, sharedFilePath)
345
- .replace(/\\/g, '/');
346
-
347
- if (!relativePath.startsWith('.')) {
348
- relativePath = './' + relativePath;
349
- }
350
-
351
- // 添加 import 和 re-export
352
- const importExport = `import type { ${usedTypes.join(', ')} } from '${relativePath}';\nexport type { ${usedTypes.join(', ')} } from '${relativePath}';\n\n`;
353
- newContent = importExport + newContent;
354
-
355
- console.log(
356
- `[rollup-dts] 🔗 Updated ${output.name}: imports ${usedTypes.join(', ')}`,
357
- );
358
- }
359
-
360
- fs.writeFileSync(output.path, newContent, 'utf-8');
361
- }
362
-
363
- return { sharedTypeNames, sharedFilePath };
364
- }
365
-
366
- export function rollupDtsPlugin(options = {}) {
367
- const {
368
- tsconfigPath = './tsconfig.json',
369
- sharedTypesOutput = null, // 例如: './dist/shared.d.ts'
370
- } = options;
371
- let resolvedConfig;
372
- let entries = [];
373
-
374
- return {
375
- name: 'vite-plugin-rollup-dts',
376
- apply: 'build',
377
- enforce: 'post',
378
-
379
- configResolved(config) {
380
- resolvedConfig = config;
381
- // 如果手动指定了 entries,使用手动配置;否则从 config 自动生成
382
- entries = options.entries || getEntriesFromConfig(config);
383
- },
384
-
385
- async closeBundle() {
386
- if (entries.length === 0) {
387
- console.log('[rollup-dts] No entries found, skipping...');
388
- return;
389
- }
390
-
391
- const projectFolder = process.cwd();
392
- const results = [];
393
- const keepFiles = [];
394
-
395
- console.log('\n[rollup-dts] Starting to bundle declaration files...');
396
-
397
- // 第一步:处理所有入口
398
- for (const entry of entries) {
399
- const result = rollupEntry(entry, projectFolder, tsconfigPath);
400
- results.push({ entry, ...result });
401
-
402
- if (result.success) {
403
- keepFiles.push(path.resolve(projectFolder, entry.output));
404
- }
405
- }
406
-
407
- // 第二步:如果有多个入口且指定了共享类型输出,提取共享类型
408
- let sharedTypeNames = [];
409
- if (sharedTypesOutput && results.filter((r) => r.success).length > 1) {
410
- console.log('[rollup-dts] 🔍 Analyzing shared types across entries...');
411
-
412
- // 读取所有成功的入口输出
413
- const outputs = results
414
- .filter((r) => r.success)
415
- .map((r) => ({
416
- name: r.entry.name,
417
- path: path.resolve(projectFolder, r.entry.output),
418
- content: fs.readFileSync(
419
- path.resolve(projectFolder, r.entry.output),
420
- 'utf-8',
421
- ),
422
- }));
423
-
424
- const { sharedTypeNames: names, sharedFilePath } = extractSharedTypes(
425
- outputs,
426
- projectFolder,
427
- sharedTypesOutput,
428
- );
429
-
430
- sharedTypeNames = names;
431
-
432
- if (sharedFilePath) {
433
- keepFiles.push(sharedFilePath);
434
- }
435
- }
436
-
437
- // 第三步:清理中间文件
438
- const dirsToKeep = new Set();
439
- for (const { entry, success } of results) {
440
- if (!success) {
441
- const entryDir = path.dirname(
442
- path.resolve(projectFolder, entry.mainEntryPoint),
443
- );
444
- dirsToKeep.add(entryDir);
445
- console.log(
446
- `[rollup-dts] 📁 Keeping directory structure for: ${entry.name}`,
447
- );
448
- }
449
- }
450
-
451
- if (dirsToKeep.size === 0) {
452
- console.log('[rollup-dts] 🧹 Cleaning up intermediate files...');
453
- const outDir = resolvedConfig?.build?.outDir || 'dist';
454
- const distDir = path.resolve(projectFolder, outDir);
455
- cleanupIntermediateFiles(distDir, keepFiles);
456
- } else {
457
- console.log(
458
- '[rollup-dts] ⚠️ Some entries failed, keeping intermediate files',
459
- );
460
- }
461
-
462
- console.log('[rollup-dts] 📊 Summary:');
463
- for (const { entry, success, skipped } of results) {
464
- if (skipped) {
465
- console.log(` ⏭️ ${entry.name} (skipped)`);
466
- } else {
467
- console.log(` ${success ? '✅' : '❌'} ${entry.name}`);
468
- }
469
- }
470
- if (sharedTypeNames.length > 0) {
471
- console.log(` 📦 shared: ${sharedTypeNames.length} types extracted`);
472
- }
473
- },
474
- };
475
- }
476
-
477
- export default rollupDtsPlugin;