TypeScript Compiler API: from string to AST

Viewed 1348

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

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
);
Related