如何生成无外部依赖的合并TypeScript类型文件?
如何从已有TypeScript类型生成无依赖的独立类型?
需求场景
假设你有以下相互依赖的TypeScript类型文件:
A.ts
export type A_Type = { some: string }
B.ts
export type B_Type = { someOther: string }
C.ts
import type { A_Type } from './A.ts' import type { B_Type } from './B.ts' export type C_Final = A_Type | B_Type
需要生成一个包含所有依赖类型内容的独立文件,最终输出示例:
export type C_Final = { some: string } | { someOther: string }
自动化解决方案
方法1:使用rollup-plugin-dts
这是最常用的类型合并工具,可自动将依赖类型内联到最终声明文件中:
- 安装依赖:
npm install --save-dev rollup rollup-plugin-dts typescript
- 创建
rollup.config.js配置文件:
import dts from 'rollup-plugin-dts'; export default { input: './C.ts', output: [{ file: './C_Compiled.d.ts', format: 'es' }], plugins: [dts()], };
- 在
package.json中添加执行脚本:
{ "scripts": { "bundle-types": "rollup -c" } }
- 运行命令生成文件:
npm run bundle-types
执行后会生成C_Compiled.d.ts,内容就是完全内联所有依赖类型的独立声明。
方法2:使用ts-morph编写自定义脚本
如果需要更灵活的类型处理逻辑,可使用ts-morph手动遍历并生成独立类型:
- 安装依赖:
npm install --save-dev ts-morph typescript
- 创建脚本文件
bundle-types.ts:
import { Project, TypeFormatFlags } from 'ts-morph'; const project = new Project(); const sourceFile = project.addSourceFileAtPath('./C.ts'); const cFinalType = sourceFile.getTypeAlias('C_Final'); // 将类型格式化为无依赖的字符串 const formattedType = cFinalType?.getType().getText(sourceFile, { typeFormatFlags: TypeFormatFlags.NoTruncation | TypeFormatFlags.IncludeTypeArguments }); // 生成独立类型文件 const outputFile = project.createSourceFile('./C_Compiled.d.ts', '', { overwrite: true }); outputFile.addTypeAlias({ name: 'C_Final', type: formattedType || '' }); outputFile.saveSync();
- 执行脚本:
npx ts-node bundle-types.ts
这种方法适合处理复杂类型场景,可自定义类型解析规则。
方法3:TypeScript编译器配合dts-bundle-generator(不推荐)
使用tsc --emitDeclarationOnly会生成保留导入的声明文件,可配合dts-bundle-generator工具合并依赖,但步骤相对繁琐,不如前两种方法高效。
注意事项
- 确保
tsconfig.json中启用declaration: true,部分工具需配合strict模式以正确解析类型。 - 复杂类型(如泛型、条件类型)可被工具自动内联,但存在循环依赖的类型需手动调整结构。
内容的提问来源于stack exchange,提问作者Philiiiiiipp
相关产品推荐
相关产品推荐

