How to generate code from AST typescript 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() { }
I think it might help you:
import * as ts from "typescript";const filename = "test.ts";const code = `const test: number = 1 + 2;`;const sourceFile = ts.createSourceFile( filename, code, ts.ScriptTarget.Latest);function printRecursiveFrom( node: ts.Node, indentLevel: number, sourceFile: ts.SourceFile) { const indentation = "-".repeat(indentLevel); const syntaxKind = ts.SyntaxKind[node.kind]; const nodeText = node.getText(sourceFile); console.log(`${indentation}${syntaxKind}: ${nodeText}`); node.forEachChild(child => printRecursiveFrom(child, indentLevel + 1, sourceFile) );}printRecursiveFrom(sourceFile, 0, sourceFile);
OUTPUT:
SourceFile: -EndOfFileToken: SourceFile: -EndOfFileToken: SourceFile: const test: number = 1 + 2; -FirstStatement: const test: number = 1 + 2; --VariableDeclarationList: const test: number = 1 + 2 ---VariableDeclaration: test: number = 1 + 2 ----Identifier: test ----NumberKeyword: number ----BinaryExpression: 1 + 2 -----FirstLiteralToken: 1 -----PlusToken: + -----FirstLiteralToken: 2 -EndOfFileToken:
UPDATE
import * as ts from "typescript";const code = `const test: number = 1 + 2;`;const transpiledCode = ts.transpileModule(code, {}).outputText;console.log(transpiledCode); // var test = 1 + 2;
Generate AST back to code
Please take a look hereI know, this is not full answer, but it might help other people to answer this question.
Unfortunately, I have no time do dig deeper(
P.S. Code taken from here
If anyone is interested in deno instead of nodejs, https://github.com/nestdotland/deno_swc is a great example. Generated and not transpiled like esprima examples.
This library is broken at the time of writing this. Check up onhttps://github.com/nestdotland/deno_swc/pull/27 or usehttps://github.com/tamusjroyce/deno_swc until the original repo isupdated.
deno 1.11.1 (release, x86_64-pc-windows-msvc) v8 9.1.269.35 typescript4.3.2
Please give a comment if this is updated so I can remove this quote.