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