Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 332
Jon Sud Avatar asked Dec 09 '20 09:12

Jon Sud


People also ask

What is AST in TypeScript?

The AST (Abstract Syntax Tree) quickly comes to your mind to approach this problem. The AST is a data structure to represent the structure of your source file in a format readable by machines. Indeed, if I throw the above example in the TypeScript AST Viewer I get immediate access to the AST.

What parser does TypeScript use?

Use babel/parser as the default parser for formatting TypeScript.

What does AST parse do?

In Python, the ast. parse() function splits the source code into tokens based on the grammar. These tokens are then transformed to build an Abstract Syntax Tree (AST). It is a tree representation of a source code.

What is AST in JavaScript?

An AST is the result of parsing code. For JavaScript, an AST is a JavaScript object containing a tree representation of your source. Before we use it, we have to create it. Depending on the code we are parsing, we choose the appropriate parser. Here since the code is ES5-compatible, we can choose the acorn parser.


1 Answers

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

like image 70
Shlomi Levi Avatar answered Oct 24 '22 09:10

Shlomi Levi