Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

how can I load a project from the source files by using ts-morph and traverse each node…

  1. User

    how can I load a project from the source files by using ts-morph and traverse each node of its AST

  2. Assistant

    You can use the ts-morph library to load a TypeScript project from source files and traverse its Abstract Syntax Tree (AST) by following these steps:

    1. Install ts-morph using npm: npm install ts-morph.

    2. Import the necessary classes and functions from ts-morph:

    import { Project, SourceFile, FunctionDeclaration } from 'ts-morph';
    
    1. Create a new Project instance and add the source files you want to analyze:
    const project = new Project();
    const sourceFile = project.addSourceFileAtPath('path/to/your/file.ts');
    
    1. Traverse the AST of the source file using the traverse method:
    sourceFile.forEachDescendant((node) => {
      // Do something with the node here
    });
    
    1. 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, including forEachChild, getChildAt, and getChildren. Choose the method that best suits your needs.

  3. User

    as this project has multiple source file, some of them are depended on others, can your script solve this and traverse each node?

  4. 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.json file in the source directory to load all the source files and their dependencies. The getSourceFiles method returns an array of SourceFile instances, which we can then traverse using the forEachDescendant method as before.

  5. User

    can I start the traversal from the entry file?

  6. 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 addSourceFileAtPath method. 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 getReferencedFiles method of the entry file to get an array of all its dependencies, and add them to the project using the addSourceFileAtPath method. We also add the entry file itself to the sourceFiles array. Finally, we traverse the AST of each source file as before.