7

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

1 Answer 1

12

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
);
Sign up to request clarification or add additional context in comments.

2 Comments

I saw codes like this online but thought this would create a file 'file.ts'. After testing it locally I found this didn't create any file. The filePath parameter confused me, but it works now. Thanks!
Yeah, it won't create a file on the file system. It's used to set the SourceFile#fileName property and to help determine the ts.ScriptKind (which is the last optional parameter on this function).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.