Skip to content

Expose module specifier resolution in TS Compiler API #36351

@mheiber

Description

@mheiber

Search Terms

compiler api, module resolution, module specifier resolution

Suggestion

Given this source:

import { bar } from "./bar";

it would be helpful if there were an API that could tell us where "./bar" points.

The most minimal way of implementing this that I know of is to make ts.SourceFile["resolvedModules"] public API. The SourceFile object already has this property, but typescript.d.ts does not expose the type for it.

Note that API Extractor already uses `ts.SourceFile["resolvedModules"].

Use Cases

What do you want to use this for?

The checker's knowledge of the module graph seems generally useful, but my specific current use case is crawling .d.ts files, given some entry points, to remove things that are not part of a package's public API. The general idea has some overlap with API Extractor but with smaller and more specific scope.

What shortcomings exist with current approaches?

typeChecker.getSymbolAtLocation seemed promising, but does not do exactly what I I'm looking for, because it follows the entire chain of aliases, skipping intermediate nodes. So the liveness analysis that I'm doing will (incorrectly) consider the intermediate nodes non-live. In the following case, It's not correct (for my purposes) to ignore "bar.ts":

// foo.ts
import { bar } from "./bar"

// bar.ts
export { bar } from "./baz"

// baz.ts
export const bar = 3;

adapted from a StackOverflow question

Examples

const sourceFile = program.getSourceFile(sourceFileName);
if (sourceFile) {
     // this code works at runtime currently
    // but requires a cast in order to acces at `resolvedModules`
    const resolvedModule = sourceFile.resolvedModules.get(moduleSpecifier);
    // ... use resolvedModule in analysis
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions