fe-stack 0.0.16 → 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.16",
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 {{ input: string, output: string }} [sharedTypes] - 共享类型配置
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 { sharedTypes, 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
- sharedTypes,
99
- }),
100
- );
101
- }
102
87
  }
103
88
 
104
89
  // 使用 mergeConfig 合并用户自定义配置
@@ -1,44 +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
- * 指定一个共享类型的入口,会被 API Extractor 单独处理
26
- * 其他入口会自动 import 这个共享类型文件
27
- * @example { input: './dist/types.d.ts', output: './dist/shared.d.ts' }
28
- */
29
- sharedTypes?: {
30
- /** 共享类型的 .d.ts 入口文件路径 */
31
- input: string;
32
- /** 合并后的输出路径 */
33
- output: string;
34
- } | null;
35
- }
36
-
37
- /**
38
- * 创建 Vite 插件用于合并 TypeScript 类型声明文件
39
- * @param options - 插件选项
40
- * @returns Vite 插件实例
41
- */
42
- export function rollupDtsPlugin(options?: RollupDtsPluginOptions): Plugin;
43
-
44
- export default rollupDtsPlugin;
@@ -1,403 +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
- */
172
- function extractExportedTypeNames(filePath) {
173
- if (!fs.existsSync(filePath)) return [];
174
-
175
- const content = fs.readFileSync(filePath, 'utf-8');
176
- const names = [];
177
-
178
- // 匹配 export declare interface/type/enum/class/namespace Name
179
- const regex =
180
- /export\s+(?:declare\s+)?(?:interface|type|enum|class|namespace)\s+(\w+)/g;
181
- let match;
182
- // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
183
- while ((match = regex.exec(content)) !== null) {
184
- names.push(match[1]);
185
- }
186
-
187
- return names;
188
- }
189
-
190
- /**
191
- * 在入口文件中添加对共享类型的 import,并移除重复的类型定义
192
- */
193
- function addSharedTypeImports(entryOutputPath, sharedTypesOutput, typeNames) {
194
- if (!fs.existsSync(entryOutputPath) || typeNames.length === 0) return;
195
-
196
- let content = fs.readFileSync(entryOutputPath, 'utf-8');
197
-
198
- // 检查文件中使用了哪些共享类型
199
- const usedTypes = typeNames.filter((name) => {
200
- // 检查是否在文件中使用了这个类型
201
- const useRegex = new RegExp(`\\b${name}\\b`);
202
- return useRegex.test(content);
203
- });
204
-
205
- if (usedTypes.length === 0) return;
206
-
207
- // 移除文件中重复的类型定义(这些类型已经在 shared.d.ts 中定义了)
208
- for (const typeName of usedTypes) {
209
- // 使用更可靠的方式:按行处理,找到类型定义的开始和结束
210
- const lines = content.split('\n');
211
- const newLines = [];
212
- let skipUntilClosingBrace = false;
213
- let braceCount = 0;
214
-
215
- for (let i = 0; i < lines.length; i++) {
216
- const line = lines[i];
217
-
218
- // 检查是否是要移除的类型定义的开始
219
- const typeDefStart = new RegExp(
220
- `^export\\s+declare\\s+(?:interface|type|enum|class|namespace)\\s+${typeName}\\b`,
221
- );
222
-
223
- if (typeDefStart.test(line) && !skipUntilClosingBrace) {
224
- // 检查是否是单行定义(type alias)
225
- if (line.includes('=') && line.includes(';')) {
226
- // 单行 type alias,直接跳过
227
- continue;
228
- }
229
-
230
- // 多行定义,开始跳过
231
- skipUntilClosingBrace = true;
232
- braceCount =
233
- (line.match(/{/g) || []).length - (line.match(/}/g) || []).length;
234
-
235
- // 如果这一行就闭合了
236
- if (braceCount <= 0 && line.includes('}')) {
237
- skipUntilClosingBrace = false;
238
- }
239
- continue;
240
- }
241
-
242
- if (skipUntilClosingBrace) {
243
- braceCount +=
244
- (line.match(/{/g) || []).length - (line.match(/}/g) || []).length;
245
- if (braceCount <= 0) {
246
- skipUntilClosingBrace = false;
247
- }
248
- continue;
249
- }
250
-
251
- newLines.push(line);
252
- }
253
-
254
- content = newLines.join('\n');
255
- }
256
-
257
- // 清理多余的空行
258
- content = content.replace(/\n{3,}/g, '\n\n').trim();
259
-
260
- // 计算相对路径
261
- const outputDir = path.dirname(entryOutputPath);
262
- const sharedFilePath = path.resolve(process.cwd(), sharedTypesOutput);
263
- let relativePath = path
264
- .relative(outputDir, sharedFilePath)
265
- .replace(/\\/g, '/');
266
-
267
- if (!relativePath.startsWith('.')) {
268
- relativePath = './' + relativePath;
269
- }
270
-
271
- // 添加 import 和 re-export 语句
272
- const importStatement = `import type { ${usedTypes.join(', ')} } from '${relativePath}';\nexport type { ${usedTypes.join(', ')} } from '${relativePath}';\n\n`;
273
- content = importStatement + content;
274
-
275
- fs.writeFileSync(entryOutputPath, content, 'utf-8');
276
- console.log(
277
- `[rollup-dts] 🔗 Added shared type imports to ${path.basename(entryOutputPath)}: ${usedTypes.join(', ')}`,
278
- );
279
- }
280
-
281
- export function rollupDtsPlugin(options = {}) {
282
- const {
283
- tsconfigPath = './tsconfig.json',
284
- sharedTypes = null, // { input: './dist/types.d.ts', output: './dist/shared.d.ts' }
285
- } = options;
286
- let resolvedConfig;
287
- let entries = [];
288
-
289
- return {
290
- name: 'vite-plugin-rollup-dts',
291
- apply: 'build',
292
- enforce: 'post',
293
-
294
- configResolved(config) {
295
- resolvedConfig = config;
296
- // 如果手动指定了 entries,使用手动配置;否则从 config 自动生成
297
- entries = options.entries || getEntriesFromConfig(config);
298
- },
299
-
300
- async closeBundle() {
301
- if (entries.length === 0) {
302
- console.log('[rollup-dts] No entries found, skipping...');
303
- return;
304
- }
305
-
306
- const projectFolder = process.cwd();
307
- const results = [];
308
- const keepFiles = [];
309
-
310
- console.log('\n[rollup-dts] Starting to bundle declaration files...');
311
-
312
- // 第一步:如果有共享类型配置,先处理共享类型
313
- let sharedTypeNames = [];
314
- if (sharedTypes) {
315
- console.log('[rollup-dts] 📦 Processing shared types first...');
316
- const sharedEntry = {
317
- name: 'shared',
318
- mainEntryPoint: sharedTypes.input,
319
- output: sharedTypes.output,
320
- };
321
- const result = rollupEntry(sharedEntry, projectFolder, tsconfigPath);
322
- if (result.success) {
323
- keepFiles.push(path.resolve(projectFolder, sharedTypes.output));
324
- // 提取共享类型文件中导出的类型名称
325
- sharedTypeNames = extractExportedTypeNames(
326
- path.resolve(projectFolder, sharedTypes.output),
327
- );
328
- console.log(
329
- `[rollup-dts] 📝 Shared types exported: ${sharedTypeNames.join(', ') || 'none'}`,
330
- );
331
- }
332
- }
333
-
334
- // 第二步:处理所有入口
335
- for (const entry of entries) {
336
- // 跳过共享类型入口(如果它也在 entries 中)
337
- if (sharedTypes && entry.mainEntryPoint === sharedTypes.input) {
338
- continue;
339
- }
340
-
341
- const result = rollupEntry(entry, projectFolder, tsconfigPath);
342
- results.push({ entry, ...result });
343
-
344
- if (result.success) {
345
- keepFiles.push(path.resolve(projectFolder, entry.output));
346
- }
347
- }
348
-
349
- // 第三步:为每个入口添加共享类型的 import
350
- if (sharedTypes && sharedTypeNames.length > 0) {
351
- console.log('[rollup-dts] 🔗 Adding shared type imports...');
352
- for (const { entry, success } of results) {
353
- if (success) {
354
- addSharedTypeImports(
355
- path.resolve(projectFolder, entry.output),
356
- sharedTypes.output,
357
- sharedTypeNames,
358
- );
359
- }
360
- }
361
- }
362
-
363
- // 第四步:清理中间文件
364
- const dirsToKeep = new Set();
365
- for (const { entry, success } of results) {
366
- if (!success) {
367
- const entryDir = path.dirname(
368
- path.resolve(projectFolder, entry.mainEntryPoint),
369
- );
370
- dirsToKeep.add(entryDir);
371
- console.log(
372
- `[rollup-dts] 📁 Keeping directory structure for: ${entry.name}`,
373
- );
374
- }
375
- }
376
-
377
- if (dirsToKeep.size === 0) {
378
- console.log('[rollup-dts] 🧹 Cleaning up intermediate files...');
379
- const outDir = resolvedConfig?.build?.outDir || 'dist';
380
- const distDir = path.resolve(projectFolder, outDir);
381
- cleanupIntermediateFiles(distDir, keepFiles);
382
- } else {
383
- console.log(
384
- '[rollup-dts] ⚠️ Some entries failed, keeping intermediate files',
385
- );
386
- }
387
-
388
- console.log('[rollup-dts] 📊 Summary:');
389
- if (sharedTypes) {
390
- console.log(` ✅ shared (${sharedTypeNames.length} types)`);
391
- }
392
- for (const { entry, success, skipped } of results) {
393
- if (skipped) {
394
- console.log(` ⏭️ ${entry.name} (skipped)`);
395
- } else {
396
- console.log(` ${success ? '✅' : '❌'} ${entry.name}`);
397
- }
398
- }
399
- },
400
- };
401
- }
402
-
403
- export default rollupDtsPlugin;