Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Compiler API: from string to AST

Is it possible to convert a string of TypeScript code snippet to AST node? In memory, without creating any a file.

like image 709
ixam Avatar asked Jul 22 '26 05:07

ixam


1 Answers

Yes, use the ts.createSourceFile function:

import * as ts from "typescript";

const sourceFile = ts.createSourceFile(
    "file.ts",                  // filePath
    "function myFunction() {}", // fileText
    ts.ScriptTarget.Latest,     // scriptTarget
    true                        // setParentNodes -- sets the `parent` property
);
like image 69
David Sherret Avatar answered Jul 24 '26 20:07

David Sherret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!