Is it possible to convert a string of TypeScript code snippet to AST node? In memory, without creating any a file.
1 Answer
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
);
2 Comments
ixam
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!
David Sherret
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).