You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用TypeScript API编程式在内存中生成.d.ts声明文件?

TypeScript 内存生成.d.ts声明文件实现方案

你需要的能力可以通过 TypeScript 官方 Compiler API 实现,核心思路是自定义编译输出回调,直接在内存中捕获声明内容,全程不会写入磁盘,生成结果和tsc命令行完全一致。

完整实现代码

import ts from 'typescript';
import type { CompilerOptions } from 'typescript';

/**
 * 生成TypeScript声明文件内容(不写入磁盘)
 * @param entryFiles 入口文件路径数组,例如 ['./src/index.ts']
 * @param compilerOptions ts编译配置,对应tsconfig.json的compilerOptions字段
 * @returns 声明文件内容集合,key为文件名,value为文件内容
 */
async function generateDeclaration(
  entryFiles: string[],
  compilerOptions: CompilerOptions = {}
): Promise<Record<string, string>> {
  // 合并必要的声明生成配置
  const mergedOptions: CompilerOptions = {
    ...compilerOptions,
    declaration: true,
    emitDeclarationOnly: true,
    noEmit: false,
    // 需合并为单文件时打开下方配置,和命令行--outFile效果一致
    // outFile: 'index.d.ts'
  };

  const dtsMap: Record<string, string> = {};

  // 创建TS编译实例
  const program = ts.createProgram(entryFiles, mergedOptions);

  // 执行编译,自定义写文件逻辑捕获内容
  program.emit(
    undefined,
    (fileName, content) => {
      if (fileName.endsWith('.d.ts')) {
        dtsMap[fileName] = content;
      }
    },
    undefined,
    undefined,
    { emitDeclarationOnly: true }
  );

  return dtsMap;
}

// 用法示例,和你预期的调用方式一致
const dtsResult = await generateDeclaration(
  ['./src/index.ts'],
  {
    // 传入你项目tsconfig.json中的其他配置即可
    strict: true,
    module: ts.ModuleKind.ESNext,
    target: ts.ScriptTarget.ESNext,
  }
);

// 直接处理生成的内容,无需读磁盘
// 配置了outFile的场景下,直接取dtsResult['index.d.ts']即可拿到完整的单文件声明内容
console.log(dtsResult['index.d.ts']);

注意事项

  • 你之前使用的tsc --declaration --emitDeclarationOnly --outFile index.d.ts命令的所有参数,都可以直接对应到compilerOptions的配置项,生成结果完全一致。
  • 默认情况下存在类型错误时不会输出声明内容,需要忽略错误强制生成的话,可以在配置中添加noEmitOnError: false。
  • 如果仅需要返回单文件的字符串内容,可以直接修改函数逻辑,固定返回dtsResult['index.d.ts']即可。

内容的提问来源于stack exchange,提问作者acfasj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:24:01