fe-stack 0.0.15 → 0.0.17

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.15",
3
+ "version": "0.0.17",
4
4
  "description": "共享的配置文件集合,用于 Vite、Tailwind、Biome、Prettier 和 TypeScript",
5
5
  "type": "module",
6
6
  "exports": {
@@ -20,6 +20,13 @@ export interface RollupDtsPluginOptions {
20
20
  entries?: Entry[];
21
21
  /** tsconfig.json 文件路径,默认为 './tsconfig.json' */
22
22
  tsconfigPath?: string;
23
+ /**
24
+ * 共享类型输出路径(多入口时使用)
25
+ * 插件会自动分析各入口输出,找出在所有入口中都存在的类型声明
26
+ * 将这些共享类型提取到指定文件,并更新各入口文件的 import
27
+ * @example './dist/shared.d.ts'
28
+ */
29
+ sharedTypesOutput?: string | null;
23
30
  }
24
31
 
25
32
  /**
@@ -94,8 +94,280 @@ function getEntriesFromConfig(config) {
94
94
  }));
95
95
  }
96
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
+
97
366
  export function rollupDtsPlugin(options = {}) {
98
- const { tsconfigPath = './tsconfig.json' } = options;
367
+ const {
368
+ tsconfigPath = './tsconfig.json',
369
+ sharedTypesOutput = null, // 例如: './dist/shared.d.ts'
370
+ } = options;
99
371
  let resolvedConfig;
100
372
  let entries = [];
101
373
 
@@ -118,83 +390,52 @@ export function rollupDtsPlugin(options = {}) {
118
390
 
119
391
  const projectFolder = process.cwd();
120
392
  const results = [];
393
+ const keepFiles = [];
121
394
 
122
395
  console.log('\n[rollup-dts] Starting to bundle declaration files...');
123
396
 
397
+ // 第一步:处理所有入口
124
398
  for (const entry of entries) {
125
- const mainEntryPointFilePath = path.resolve(
126
- projectFolder,
127
- entry.mainEntryPoint,
128
- );
399
+ const result = rollupEntry(entry, projectFolder, tsconfigPath);
400
+ results.push({ entry, ...result });
129
401
 
130
- if (!fs.existsSync(mainEntryPointFilePath)) {
131
- console.warn(
132
- `[rollup-dts] ⚠️ Skipping ${entry.name}: ${entry.mainEntryPoint} not found`,
133
- );
134
- continue;
402
+ if (result.success) {
403
+ keepFiles.push(path.resolve(projectFolder, entry.output));
135
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
+ }));
136
423
 
137
- console.log(`[rollup-dts] 📦 Rolling up types for: ${entry.name}`);
138
-
139
- const config = {
140
- ...baseConfig,
141
- compiler: {
142
- tsconfigFilePath: `<projectFolder>/${tsconfigPath}`,
143
- },
144
- mainEntryPointFilePath: `<projectFolder>/${entry.mainEntryPoint}`,
145
- dtsRollup: {
146
- enabled: true,
147
- untrimmedFilePath: `<projectFolder>/${entry.output}`,
148
- },
149
- };
150
-
151
- // 用安全的文件名(将 / 替换为 -)
152
- const safeName = entry.name.replace(/\//g, '-');
153
- const tempConfigPath = path.resolve(
424
+ const { sharedTypeNames: names, sharedFilePath } = extractSharedTypes(
425
+ outputs,
154
426
  projectFolder,
155
- `api-extractor.${safeName}.tmp.json`,
427
+ sharedTypesOutput,
156
428
  );
157
- fs.writeFileSync(tempConfigPath, JSON.stringify(config, null, 2));
158
-
159
- let success = false;
160
- try {
161
- const extractorConfig =
162
- ExtractorConfig.loadFileAndPrepare(tempConfigPath);
163
- const extractorResult = Extractor.invoke(extractorConfig, {
164
- localBuild: true,
165
- showVerboseMessages: false,
166
- });
167
429
 
168
- if (extractorResult.succeeded) {
169
- console.log(
170
- `[rollup-dts] ✅ ${entry.name}: types rolled up successfully`,
171
- );
172
- success = true;
173
- } else {
174
- console.warn(
175
- `[rollup-dts] ⚠️ ${entry.name}: API Extractor completed with warnings/errors`,
176
- );
177
- if (fs.existsSync(path.resolve(projectFolder, entry.output))) {
178
- success = true;
179
- }
180
- }
181
- } catch (error) {
182
- console.warn(
183
- `[rollup-dts] ⚠️ ${entry.name}: Error during rollup, keeping original .d.ts files`,
184
- );
185
- console.warn(` ${error instanceof Error ? error.message : error}`);
186
- } finally {
187
- if (fs.existsSync(tempConfigPath)) {
188
- fs.unlinkSync(tempConfigPath);
189
- }
190
- }
430
+ sharedTypeNames = names;
191
431
 
192
- results.push({ entry, success });
432
+ if (sharedFilePath) {
433
+ keepFiles.push(sharedFilePath);
434
+ }
193
435
  }
194
436
 
195
- // Determine which directories to keep
437
+ // 第三步:清理中间文件
196
438
  const dirsToKeep = new Set();
197
-
198
439
  for (const { entry, success } of results) {
199
440
  if (!success) {
200
441
  const entryDir = path.dirname(
@@ -207,15 +448,11 @@ export function rollupDtsPlugin(options = {}) {
207
448
  }
208
449
  }
209
450
 
210
- // Clean up only if all entries succeeded
211
451
  if (dirsToKeep.size === 0) {
212
452
  console.log('[rollup-dts] 🧹 Cleaning up intermediate files...');
213
453
  const outDir = resolvedConfig?.build?.outDir || 'dist';
214
454
  const distDir = path.resolve(projectFolder, outDir);
215
- cleanupIntermediateFiles(
216
- distDir,
217
- entries.map((e) => path.resolve(projectFolder, e.output)),
218
- );
455
+ cleanupIntermediateFiles(distDir, keepFiles);
219
456
  } else {
220
457
  console.log(
221
458
  '[rollup-dts] ⚠️ Some entries failed, keeping intermediate files',
@@ -223,8 +460,15 @@ export function rollupDtsPlugin(options = {}) {
223
460
  }
224
461
 
225
462
  console.log('[rollup-dts] 📊 Summary:');
226
- for (const { entry, success } of results) {
227
- console.log(` ${success ? '✅' : '❌'} ${entry.name}`);
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`);
228
472
  }
229
473
  },
230
474
  };
@@ -11,9 +11,12 @@ import { rollupDtsPlugin } from './vite-plugin-rollup-dts.js';
11
11
  /**
12
12
  * @typedef {import('vite').UserConfig} UserConfig
13
13
  * @typedef {import('vite-plugin-dts').PluginOptions} DtsPluginOptions
14
+ * @typedef {Object} RollupDtsOptions
15
+ * @property {string} [tsconfigPath] - tsconfig.json 路径
16
+ * @property {string} [sharedTypesOutput] - 共享类型输出路径(多入口时)
14
17
  * @typedef {Object} CreateBaseConfigOptions
15
18
  * @property {'app' | 'lib'} [mode] - 构建模式:'app' 为 Vue 应用,'lib' 为库打包
16
- * @property {Partial<DtsPluginOptions>} [dtsConfig] - vite-plugin-dts 配置(仅 lib 模式),会与默认配置合并
19
+ * @property {Partial<DtsPluginOptions> & RollupDtsOptions} [dtsConfig] - vite-plugin-dts 配置(仅 lib 模式),会与默认配置合并
17
20
  * @property {UserConfig} [viteConfig] - 额外的 Vite 配置,会与基础配置合并
18
21
  */
19
22
 
@@ -67,6 +70,9 @@ export function createBaseConfig(dirname, options = {}) {
67
70
 
68
71
  // Lib mode: 提供默认配置
69
72
  if (mode === 'lib') {
73
+ // 提取 rollupDts 专用配置
74
+ const { sharedTypesOutput, tsconfigPath, ...dtsOnlyConfig } = dtsConfig;
75
+
70
76
  baseConfig.build = {
71
77
  copyPublicDir: false,
72
78
  lib: {
@@ -81,12 +87,17 @@ export function createBaseConfig(dirname, options = {}) {
81
87
  dts({
82
88
  include: ['src/**/*.ts'],
83
89
  root: dirname,
84
- ...dtsConfig,
90
+ ...dtsOnlyConfig,
85
91
  rollupTypes: false,
86
92
  }),
87
93
  );
88
94
  if (dtsConfig.rollupTypes) {
89
- baseConfig.plugins.push(rollupDtsPlugin());
95
+ baseConfig.plugins.push(
96
+ rollupDtsPlugin({
97
+ tsconfigPath,
98
+ sharedTypesOutput,
99
+ }),
100
+ );
90
101
  }
91
102
  }
92
103