Search code examples
typescripttypescript-compiler-api

generate d.ts programmatically (in memory)


I know that we could use tsc --declaration --emitDeclarationOnly --outFile index.d.ts to generate declaration file. But how can I generate it programmatically? For example:

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

I don't want d.ts output into a file. I am kind of stuck and don't know how to get started


Solution

  • To generate it programmatically you will need to:

    1. Setup a ts.Program based on a tsconfig.json file.
    2. Emit the program by calling Program#emit with emitOnlyDtsFiles set to true and provide a custom writeFile callback to capture the output in memory.

    Here's an example using @ts-morph/bootstrap because I have no idea how to easily setup a program with a tsconfig.json file using only the TypeScript Compiler API (it takes a lot of code from my understanding and this is easier):

    // 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