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
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.
Use babel/parser as the default parser for formatting TypeScript.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With