Hof*_*off 7 static-analysis typescript visual-studio-code
我喜欢VS Code中的Typescript的一个方面是能够使用Shift + F12(或右键单击)查找对函数的所有引用.是否有可能以编程方式进入此映射,或以某种方式导出它?
输出将包含以下信息:
fileA.ClassA.methodA is referenced in fileB.ClassB.methodB
Run Code Online (Sandbox Code Playgroud)
由于这很容易"手工",我希望它也可以以编程方式完成,但我不确定哪些接口可用.
编辑
由于这个问题正在接受投票,我想提一下,stackoverflow是VS Code建议提问的地方:
对于最灵活的解决方案,您需要使用 TypeScript Language Service API。你想要的具体方法是findReferences。在超高级别上,您的程序将如下所示:
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());
Run Code Online (Sandbox Code Playgroud)
然而,根据您的需求,这可能有点过分了。设置语言服务也可能相当困难。
相反,您可以重用 VS Code 的查找所有引用逻辑。为此,请创建一个执行vscode.executeReferenceProvider命令的 VS Code 扩展
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
}
}
Run Code Online (Sandbox Code Playgroud)
这意味着您必须将程序作为 VS Code 扩展来运行,但设置要容易得多
您需要使用Compiler API。它允许您使用 JS API 引用 TypeScript 的所有功能(tsc “只是”命令行版本),包括模块层次结构。没看源码,不过很有可能是TS VSC语言服务器内部使用的就是这个。
最坏的情况是,您会获得一个文件的 AST,因此您可以以任何您希望的方式搜索出现的情况。
小智 5
我在同一个任务中,我通过了你的帖子,我终于使用ts-morph得到了它,这里很简单。
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");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
774 次 |
| 最近记录: |