Typescript: accessing VS Code's "Find All References" programatically
You need to use the Compiler API. It allows you to reference all features of TypeScript with a JS API (tsc is "just" the command line version), including module hierarchy. I haven't looked at the source, but it's very likely that this is what the TS VSC language server uses internally.
Worst case scenario, you get an AST of a file so you can search for occurrences in any way you wish.
For the most flexible solution, you'll want to use the TypeScript Language Service API. The specific method you want is findReferences
. At a super high level, your program will look like this:
import ts from 'typescript'
// create service host
// see https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#incremental-build-support-using-the-language-services
const services = ts.createLanguageService(servicesHost, ts.createDocumentRegistry());
However that may be overkill depending on your needs. Setting up the language service can also be rather difficult.
Instead, you may be able to reuse VS Code's find all references logic. To do this, create a VS Code extension that executes the vscode.executeReferenceProvider
command
import * vscode from 'vscode';
export async function activate() {
const referenceLocation = await vscode.commands.executeCommand('vscode.executeReferenceProvider',
tsDocumentURI, // Uri of document containing symbol to find references for
new vscode.Position(0, 10), // Position (line, column) of symbol find references for
);
for (const location of referenceLocation) {
// do something with the locations, such as writing them to disk as json
}
}
This means that you will have to run your program as a VS Code extension, but it is far easier to setup
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");
}
}
}
}