how can I load a project from the source files by using ts-morph and traverse each node…
- User
how can I load a project from the source files by using ts-morph and traverse each node of its AST
- Assistant
You can use the
ts-morphlibrary to load a TypeScript project from source files and traverse its Abstract Syntax Tree (AST) by following these steps:-
Install
ts-morphusing npm:npm install ts-morph. -
Import the necessary classes and functions from
ts-morph:
import { Project, SourceFile, FunctionDeclaration } from 'ts-morph';- Create a new
Projectinstance and add the source files you want to analyze:
const project = new Project(); const sourceFile = project.addSourceFileAtPath('path/to/your/file.ts');- Traverse the AST of the source file using the
traversemethod:
sourceFile.forEachDescendant((node) => { // Do something with the node here });- In the callback function passed to
forEachDescendant, you can access the properties of the nodes and analyze them as needed. For example, you can check if a node is a function declaration and get its name:
sourceFile.forEachDescendant((node) => { if (node instanceof FunctionDeclaration) { const functionName = node.getName(); console.log(`Found function: ${functionName}`); } });Note that there are multiple ways to traverse the AST using
ts-morph, includingforEachChild,getChildAt, andgetChildren. Choose the method that best suits your needs. -
- User
as this project has multiple source file, some of them are depended on others, can your script solve this and traverse each node?
- Assistant
Yes, the script can handle multiple source files and dependencies between them. Here's an updated version of the script that loads all the source files in a directory and their dependencies, and traverses each node of their AST:
import { Project, SourceFile, FunctionDeclaration } from 'ts-morph'; import * as path from 'path'; // Directory containing the source files const sourceDir = './src'; // Create a new project and add all the source files in the directory const project = new Project({ tsConfigFilePath: path.join(sourceDir, 'tsconfig.json') }); // Get all the source files and their dependencies const sourceFiles = project.getSourceFiles(); // Traverse the AST of each source file sourceFiles.forEach((sourceFile) => { // Do something with the source file sourceFile.forEachDescendant((node) => { // Do something with the node if (node instanceof FunctionDeclaration) { const functionName = node.getName(); console.log(`Found function: ${functionName}`); } }); });In this updated version of the script, we use the
tsconfig.jsonfile in the source directory to load all the source files and their dependencies. ThegetSourceFilesmethod returns an array ofSourceFileinstances, which we can then traverse using theforEachDescendantmethod as before. - User
can I start the traversal from the entry file?
- Assistant
Yes, you can start the traversal from the entry file by specifying the path to the entry file when adding it to the project using the
addSourceFileAtPathmethod. Here's an updated version of the script that loads only the entry file and its dependencies, and traverses each node of their AST:import { Project, SourceFile, FunctionDeclaration } from 'ts-morph'; import * as path from 'path'; // Path to the entry file const entryFilePath = './src/index.ts'; // Create a new project and add the entry file and its dependencies const project = new Project({ tsConfigFilePath: path.join(path.dirname(entryFilePath), 'tsconfig.json') }); const entryFile = project.addSourceFileAtPath(entryFilePath); const sourceFiles = entryFile.getReferencedFiles().map((ref) => { return project.addSourceFileAtPath(path.join(path.dirname(entryFilePath), ref.getFileName())); }); sourceFiles.push(entryFile); // Traverse the AST of each source file sourceFiles.forEach((sourceFile) => { // Do something with the source file sourceFile.forEachDescendant((node) => { // Do something with the node if (node instanceof FunctionDeclaration) { const functionName = node.getName(); console.log(`Found function: ${functionName}`); } }); });In this updated version of the script, we use the
getReferencedFilesmethod of the entry file to get an array of all its dependencies, and add them to the project using theaddSourceFileAtPathmethod. We also add the entry file itself to thesourceFilesarray. Finally, we traverse the AST of each source file as before.