以编程方式生成 d.ts(在内存中)

generate d.ts programmatically (in memory)

我知道我们可以使用 tsc --declaration --emitDeclarationOnly --outFile index.d.ts 生成声明文件。但是我怎样才能以编程方式生成它呢?例如:

import ts from 'typescript'
const dts = await ts.generateDdeclaration(/* tsconfig.json */);
// then do some stuff with dts, like in webpack plugin

我不想 d.ts 输出到文件中。我有点卡住了,不知道如何开始

要以编程方式生成它,您需要:

  1. 根据 tsconfig.json 文件设置 ts.Program
  2. 通过调用 Program#emit 并将 emitOnlyDtsFiles 设置为 true 来发出程序,并提供自定义 writeFile 回调以在内存中捕获输出。

这是一个使用 @ts-morph/bootstrap 的示例,因为我不知道如何仅使用 TypeScript 编译器 API 使用 tsconfig.json 文件轻松设置程序(这需要大量代码根据我的理解,这更容易):

// or import as "@ts-morph/bootstrap" if you're using node/npm
import {
  createProjectSync,
  ts,
} from "https://deno.land/x/ts_morph@12.0.0/bootstrap/mod.ts";

const project = createProjectSync({
  tsConfigFilePath: "tsconfig.json",
});

const files = new Map<string, string>();
const program = project.createProgram();
program.emit(
  undefined,
  (fileName, data, writeByteOrderMark) => {
    if (writeByteOrderMark) {
      data = "\uFEFF" + data;
    }
    files.set(fileName, data);
  },
  undefined,
  /* emitOnlyDtsFiles */ true,
  // custom transformers could go here in this argument
);

// use files here