Skip to content

Instantly share code, notes, and snippets.

@johnrees
Created December 2, 2019 16:30
Show Gist options
  • Save johnrees/157772e6a136e4365f91a86aafe044a2 to your computer and use it in GitHub Desktop.
Save johnrees/157772e6a136e4365f91a86aafe044a2 to your computer and use it in GitHub Desktop.
ts-morph ts-simple-ast
// https://ts-ast-viewer.com/#code/GYVwdgxgLglg9mABACwKYBt1wBRgIYC2qAXIgM5QBOMYA5gDSJ5hxRqWIC8iA5GpnB4BKUhWp1EAbwBQiRJVRQQlJAAN+WRABJJ+IgF9VAbmn6gA
import { Project, SyntaxKind } from "ts-morph";
const project = new Project({});
project.addExistingSourceFiles("./src/thing.ts");
const node = project.getSourceFileOrThrow("./src/thing.ts");
const result = node.forEachDescendant((node, traversal) => {
switch (node.getKind()) {
case SyntaxKind.ImportDeclaration:
const ob = {} as any;
node.forEachChild(node => {
ob[SyntaxKind[node.getKind()]] = node.getText();
// console.log(node.getText());
// console.log(SyntaxKind[node.getKind()]);
});
console.log({
import: ob.ImportClause,
from: ob.StringLiteral
});
break;
case SyntaxKind.FunctionDeclaration:
const fnName = node.getFirstChildByKindOrThrow(SyntaxKind.Identifier);
console.log({ fnName: fnName.getText() });
node
.getChildrenOfKind(SyntaxKind.Parameter)
.forEach(v =>
v
.getChildrenOfKind(SyntaxKind.Identifier)
.forEach(v => console.log(v.getText()))
);
break;
// case SyntaxKind.ClassDeclaration:
// // skips traversal of the current node's descendants
// traversal.skip();
// break;
// case SyntaxKind.Parameter:
// // skips traversal of the current node's descendants and its siblings and all their descendants
// traversal.up();
// break;
// case SyntaxKind.FunctionDeclaration:
// // stops traversal completely
// traversal.stop();
// break;
// case SyntaxKind.InterfaceDeclaration:
// // stops traversal completely and returns this value
// return node;
}
return undefined;
});
console.log({ result });
function hello(name: string, another): string {
return `hello ${name}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment