Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: accessing VS Code's "Find All References" programatically

One of the things I like about Typescript in VS Code is the ability to find all references to a function with Shift+F12 (or right-click). Is it possible to get to this mapping programatically, or to export it somehow?

The output would contain information like:

fileA.ClassA.methodA is referenced in fileB.ClassB.methodB

Since this is easy to do 'by hand', I'm hoping that it can also done programatically, but I'm not sure what interfaces are available.

enter image description here

like image 740
Hoff Avatar asked Jan 11 '18 12:01

Hoff


People also ask

How do you find all references in VS code?

You can use the Find All References command to find where particular code elements are referenced throughout your codebase. The Find All References command is available on the context (right-click) menu of the element you want to find references to. Or, if you are a keyboard user, press Shift + F12.

How do you find out where a function is called in Vscode?

You can CTRL+CLICK (Windows) or CMD+CLICK (Mac) on the function name and look on the right column. Save this answer.

What is CodeLens in Visual Studio code?

CodeLens lets you stay focused on your work while you find out what happened to your code–without leaving the editor. You can find references to a piece of code, changes to your code, linked bugs, work items, code reviews, and unit tests.


1 Answers

I was in the same quest and I passed by your post, I finally got it using ts-morph, here is as simple as it gets.

import { Project } from "ts-morph";
const project = new Project({
    tsConfigFilePath: "<yourproject>\\tsconfig.json",
});

for(const sourceFile of project.getSourceFiles()){
    for(const classDeclaration  of sourceFile.getClasses()){
        console.log("---------")
        console.log("Class ",classDeclaration.getName())
        console.log("---------")
        const referencedSymbols = classDeclaration.findReferences();

        for (const referencedSymbol of referencedSymbols) {
            for (const reference of referencedSymbol.getReferences()) {
                console.log("---------")
                console.log("REFERENCE")
                console.log("---------")
                console.log("File path: " + reference.getSourceFile().getFilePath());
                console.log("Start: " + reference.getTextSpan().getStart());
                console.log("Length: " + reference.getTextSpan().getLength());
                console.log("Parent kind: " + reference.getNode().getParentOrThrow().getKindName());
                console.log("\n");
            }
        }
    }
}
like image 183
Carlo Capuano Avatar answered Sep 17 '22 18:09

Carlo Capuano