Typescript: API about Identifier's scope

Created on 21 Oct 2018  路  1Comment  路  Source: microsoft/TypeScript

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

API Experience Enhancement Suggestion

Most helpful comment

I have written a utility function to get all references to a given declaration.

import {collectVariableUsage} from 'tsutils';

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

Currently you can only look up the uses of a declaration. A reverse lookup is not possible. It also doesn't tell if an identifier is in scope at a given location.
Tough I'm planning on improving the API to make it more powerful and easier to use: https://github.com/ajafff/tsutils/issues/38

>All comments

I have written a utility function to get all references to a given declaration.

import {collectVariableUsage} from 'tsutils';

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

Currently you can only look up the uses of a declaration. A reverse lookup is not possible. It also doesn't tell if an identifier is in scope at a given location.
Tough I'm planning on improving the API to make it more powerful and easier to use: https://github.com/ajafff/tsutils/issues/38

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Zlatkovsky picture Zlatkovsky  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

manekinekko picture manekinekko  路  3Comments

uber5001 picture uber5001  路  3Comments