I'm relatively new to doing stuff with the Typescript Compiler. I'm trying to write some code that:
Given a .ts
file, it can extract all the functions from it. Specifically, I'm trying to achieve an array of objects of the type { funcName: string, funcBody: string }
where funcName
is the name of the function, and funcBody
is the overall code of the function (including the function declaration).
Currently, I have this simple piece of code
export async function extract(file: string) {
const program = ts.createProgram([file], { allowJs: true });
const sourceFile = program.getSourceFile(file);
if (!sourceFile) return [];
const output: any = [];
ts.forEachChild(sourceFile, (node) => {
if (ts.isFunctionDeclaration(node)) {
const funcName = node.name ? node.name.text : "<anonymous>";
const funcBody = node.body;
console.log({ funcName, funcBody });
}
});
}
It is able to get the funcName
just fine, but I am unable to figure out how to get the actual funcBody
.
and funcBody is the overall code of the function (including the function declaration).
If you want to get the text of the function declaration without leading trivia (comments & whitespace), then you can do:
if (ts.isFunctionDeclaration(node)) {
const funcName = node.name ? node.name.text : "<anonymous>";
const funcDecl = node.getText(sourceFile);
console.log({ funcName, funcDecl });
}
To get just the function body text, use node.body.getText(sourceFile).slice(1, -1).trim()
(slice to remove the surrounding braces).
A good resource is: https://ts-ast-viewer.com/#code/GYVwdgxgLglg9mABAUwB4EMC2AHANsgCgEpEBvAKESsQgQGc58A6XOAcwIFYiBucgXyA (It will tell you the result of .getText()
in the rightmost column)