1

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

1 Answer 1

3

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/[email protected]/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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.