TypeScript 关于标识符范围的API

yfwxisqw  于 9个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(94)

I want to write a CustomTransformers for my webpack loader config.
Babel's visitors have API about scope
If I get a path of ImportDeclaration import * as React from "react" , I can using path.scope.getBinding('React').referencePaths to get all reference paths using React.
Is there any API in TypeScript to get identifier's scope or referenced nodes/identifiers?
Also, Is there any API in TypeScript to get ImportDeclaration's moduleSpecifier's resolved source file? for example import * as React from "react" 's resolved source file is /home/me/my-ts-project/node_modules/react/cjs/react.development.js

nfg76nw0

nfg76nw01#

我已经编写了一个实用函数来获取给定声明的所有引用。

  1. import {collectVariableUsage} from 'tsutils';
  2. /**
  3. *`identifier` needs to be the name of the declaration and be located within `sourceFile`.
  4. * Note that this only works on one source file at a time and can therefore not detect references to global variables in other files.
  5. */
  6. function getUses(sourceFile: ts.SourceFile, identifier: ts.Identifier) {
  7. // you might want to cache the result of `collectVariableUsage`
  8. return collectVariableUsage(sourceFile).get(identifier)!.uses;
  9. }

目前,您只能查找声明的使用情况。无法进行反向查找。它也无法告诉在给定位置是否存在标识符。
尽管我计划改进API以使其更具功能性和易于使用: ajafff/tsutils#38

svujldwt

svujldwt2#

resolveName 现在是 TypeChecker 上的 API:
TypeScript/lib/typescript.d.ts
第 6884 行 in 6ea273c
| | resolveName(name: string,location: Node|undefined,meaning: SymbolFlags,excludeGlobals: boolean): Symbol|undefined; |
ProgramresolveModuleNames:
TypeScript/lib/typescript.d.ts
第 10216 行 in 6ea273c
| | resolveModuleNames?(moduleNames: string[],containingFile: string,reusedNames: string[]|undefined,redirectedReference: ResolvedProjectReference|undefined,options: CompilerOptions,containingSourceFile?: SourceFile): (ResolvedModule|undefined)[]; |
我认为这些已经足够接近你可能要找的答案了,但不是百分之百确定。

相关问题