Search code examples
typescriptabstract-syntax-tree

How to generate code from AST typescript parser?


After I read the Using the Compiler API article, I could get the AST from string-code.

But when I try to generate the code (by escodegen) from AST (not transpile it) to code I got an error:

Unknown node type: undefined

Is there a way to generate the ast to the code?

import * as fs from "fs";
import escodegen from "escodegen";
import * as ts from "typescript";

const code = `
 function foo() { }
`;

const node = ts.createSourceFile("x.ts", code, ts.ScriptTarget.Latest);

console.log({ node });

const x = escodegen.generate(node);

console.log({ x });

codesandbox.io


Solution

  • You can do it by createPrinter and pass node to printNode.

    Here working example:

    const code = `
     function foo() { }
    `;
    
    const node = ts.createSourceFile("x.ts", code, ts.ScriptTarget.Latest);
    const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
    
    const result = printer.printNode(ts.EmitHint.Unspecified, node, node);
    console.log(result); // function foo() { }
    

    codesandbox