TypeScript module resolution fundamentals

Tracing

Use the --traceResolution compiler option to debug module resolution.

Classic (legacy) Module Resolution

This is available for backward compatibility.

Node (default) Module Resolution

./root/src/moduleA.ts will resolve import { B } from "./moduleB" as follows:

  • ./root/src/moduleB.ts or
  • ./root/src/moduleB/package.json > typings or
  • ./root/src/moduleB/index.ts.

It will resolve import { B } from "moduleB" similarly, but will look inside node_modules starting on the same level as moduleA and then walking up the directory tree.

Note also that .ts may also be the .tsx or .d.ts suffixes.

Ambient Modules

Ambient modules allows us to declare more than one module per file. We declare the module name in quotes and put the module inside brackets.

/// fooBarBaz.d.ts

declare module "foo" {  
    export class SomeClass {}
}

declare module "bar" {  
    export class OtherClass {}
}

declare module "baz" {  
    export class AnotherClass {}
}

Relative Imports

If it starts with ./ ../ or / then it is a relative import.

  • resolved relative to the importing file
  • cannot resolve to ambient modules
  • use for your own modules that have a guaranteed runtime path

Non-relative Imports

  • resolved relative to a baseUrl or via path mapping
  • can resolve to ambient modules

See https://www.typescriptlang.org/docs/handbook/module-resolution.html