Module Resolution | Typescript

Module resolution is the process the compiler uses to figure out what an import refers to.
Consider an import statement like import { a } from "moduleA";
in order to check any use of a, the compiler needs to know exactly what it represents, and will need to check its definition moduleA.

First, the compiler will try to locate a file that represents the imported module. To do so the compiler follows one of two different strategies: Classic or Node. These strategies tell the compiler where to look for moduleA.

If that didn't work and if the module name is non-relative (and in the case of "moduleA", it is), then the compiler will attempt to locate an ambient module declaration. We'll cover non-relative imports next.

Finally, if the compiler could not resolve the module, it will log an error. In this case, the error would be something like error TS2307: Cannot find module 'moduleA'.

Relative vs. Non-relative module imports#

A relative import is one that starts with /, ./ or ../. Some examples include:

  • import Entry from "./components/Entry";
  • import { DefaultHeaders } from "../constants/http";
  • import "/mod";

Any other import is considered non-relative. Some examples include:

  • import * as $ from "jquery";
  • import { Component } from "@angular/core";

A non-relative import can be resolved relative to baseUrl, or through path mapping, which we'll cover below. They can also resolve to ambient module declarations. Use non-relative paths when importing any of your external dependencies.

Module Resolution Strategies#

There are two possible module resolution strategies: Node and Classic. You can use the --moduleResolution flag to specify the module resolution strategy. If not specified, the default is Classic for --module AMD | System | ES2015 or Node otherwise.

Classic#

Nowadays, this strategy is mainly present for backward compatibility.

Relative import#

So import { b } from "./moduleB" in source file /root/src/folder/A.ts would result in the following lookups:

  1. /root/src/folder/moduleB.ts
  2. /root/src/folder/moduleB.d.ts

Non-relative module imports#

A non-relative import to moduleB such as import { b } from "moduleB", in a source file /root/src/folder/A.ts, would result in attempting the following locations for locating "moduleB":

  1. /root/src/folder/moduleB.ts
  2. /root/src/folder/moduleB.d.ts
  3. /root/src/moduleB.ts
  4. /root/src/moduleB.d.ts
  5. /root/moduleB.ts
  6. /root/moduleB.d.ts
  7. /moduleB.ts
  8. /moduleB.d.ts

Node#

The full Node.js resolution algorithm is outlined in Node.js module documentation.

Relative paths#

As an example, let's consider a file located at /root/src/moduleA.js, which contains the import var x = require("./moduleB"); Node.js resolves that import in the following order:

  1. Ask the file named /root/src/moduleB.js, if it exists.

  2. Ask the folder /root/src/moduleB if it contains a file named package.json that specifies a "main" module. In our example, if Node.js found the file /root/src/moduleB/package.json containing { "main": "lib/mainModule.js" }, then Node.js will refer to /root/src/moduleB/lib/mainModule.js.

  3. Ask the folder /root/src/moduleB if it contains a file named index.js. That file is implicitly considered that folder's "main" module.

Non-Relative paths#

Following up our example above, consider if /root/src/moduleA.js instead used a non-relative path and had the import var x = require("moduleB");. Node would then try to resolve moduleB to each of the locations until one worked.

  1. /root/src/node_modules/moduleB.js
  2. /root/src/node_modules/moduleB/package.json (if it specifies a "main" property)
  3. /root/src/node_modules/moduleB/index.js

  4. /root/node_modules/moduleB.js
  5. /root/node_modules/moduleB/package.json (if it specifies a "main" property)
  6. /root/node_modules/moduleB/index.js

  7. /node_modules/moduleB.js
  8. /node_modules/moduleB/package.json (if it specifies a "main" property)
  9. /node_modules/moduleB/index.js

How TypeScript resolves modules#

TypeScript will mimic the Node.js run-time resolution strategy in order to locate definition files for modules at compile-time.
To accomplish this, TypeScript overlays the TypeScript source file extensions (.ts, .tsx, and .d.ts) over Node's resolution logic.
TypeScript will also use a field in package.json named "types" to mirror the purpose of "main" - the compiler will use it to find the "main" definition file to consult.

For example, an import statement like import { b } from "./moduleB" in /root/src/moduleA.ts would result in attempting the following locations for locating "./moduleB":

  1. /root/src/moduleB.ts
  2. /root/src/moduleB.tsx
  3. /root/src/moduleB.d.ts
  4. /root/src/moduleB/package.json (if it specifies a "types" property)
  5. /root/src/moduleB/index.ts
  6. /root/src/moduleB/index.tsx
  7. /root/src/moduleB/index.d.ts

Recall that Node.js looked for a file named moduleB.js, then an applicable package.json, and then for an index.js.

Similarly, a non-relative import will follow the Node.js resolution logic, first looking up a file, then looking up an applicable folder. So import { b } from "moduleB" in source file /root/src/moduleA.ts would result in the following lookups:

  1. /root/src/node_modules/moduleB.ts
  2. /root/src/node_modules/moduleB.tsx
  3. /root/src/node_modules/moduleB.d.ts
  4. /root/src/node_modules/moduleB/package.json (if it specifies a "types" property)
  5. /root/src/node_modules/@types/moduleB.d.ts
  6. /root/src/node_modules/moduleB/index.ts
  7. /root/src/node_modules/moduleB/index.tsx
  8. /root/src/node_modules/moduleB/index.d.ts

  9. /root/node_modules/moduleB.ts
  10. /root/node_modules/moduleB.tsx
  11. /root/node_modules/moduleB.d.ts
  12. /root/node_modules/moduleB/package.json (if it specifies a "types" property)
  13. /root/node_modules/@types/moduleB.d.ts
  14. /root/node_modules/moduleB/index.ts
  15. /root/node_modules/moduleB/index.tsx
  16. /root/node_modules/moduleB/index.d.ts

  17. /node_modules/moduleB.ts
  18. /node_modules/moduleB.tsx
  19. /node_modules/moduleB.d.ts
  20. /node_modules/moduleB/package.json (if it specifies a "types" property)
  21. /node_modules/@types/moduleB.d.ts
  22. /node_modules/moduleB/index.ts
  23. /node_modules/moduleB/index.tsx
  24. /node_modules/moduleB/index.d.ts

Additional module resolution flags#

Base URL#

Setting baseUrl informs the compiler where to find modules. All module imports with non-relative names are assumed to be relative to the baseUrl.

Value of baseUrl is determined as either:

  • value of baseUrl command line argument (if given path is relative, it is computed based on current directory)
  • value of baseUrl property in 'tsconfig.json' (if given path is relative, it is computed based on the location of 'tsconfig.json')

You can find more documentation on baseUrl in RequireJS and SystemJS documentation.

Path mapping#

Sometimes modules are not directly located under baseUrl. For instance, an import to a module "jquery" would be translated at runtime to "node_modules/jquery/dist/jquery.slim.min.js". Loaders use a mapping configuration to map module names to files at run-time, see RequireJs documentation and SystemJS documentation.

The TypeScript compiler supports the declaration of such mappings using "paths" property in tsconfig.json files. Here is an example for how to specify the "paths" property for jquery.

{
"compilerOptions": {
"baseUrl": ".", // This must be specified if "paths" is.
"paths": {
"jquery": ["node_modules/jquery/dist/jquery"] // This mapping is relative to "baseUrl"
}
}
}

Please notice that "paths" are resolved relative to "baseUrl". When setting "baseUrl" to another value than ".", i.e. the directory of tsconfig.json, the mappings must be changed accordingly. Say, you set "baseUrl": "./src" in the above example, then jquery should be mapped to "../node_modules/jquery/dist/jquery".

Using "paths" also allows for more sophisticated mappings including multiple fall back locations. Consider a project configuration where only some modules are available in one location, and the rest are in another. A build step would put them all together in one place. The project layout may look like:

projectRoot
├── folder1
│ ├── file1.ts (imports 'folder1/file2' and 'folder2/file3')
│ └── file2.ts
├── generated
│ ├── folder1
│ └── folder2
│ └── file3.ts
└── tsconfig.json

The corresponding tsconfig.json would look like:

{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": [
"*",
"generated/*"
]
}
}
}

This tells the compiler for any module import that matches the pattern "*" (i.e. all values), to look in two locations:

  1. "*": meaning the same name unchanged, so map <moduleName> => <baseUrl>/<moduleName>
  2. "generated/*" meaning the module name with an appended prefix "generated", so map <moduleName> => <baseUrl>/generated/<moduleName>

Following this logic, the compiler will attempt to resolve the two imports as such:

import 'folder2/file3':

  1. pattern '*' is matched and wildcard captures the whole module name
  2. try first substitution in the list: '*' -> folder2/file3
  3. result of substitution is non-relative name - combine it with baseUrl -> projectRoot/folder2/file3.ts.
  4. File does not exist, move to the second substitution
  5. second substitution 'generated/*' -> generated/folder2/file3
  6. result of substitution is non-relative name - combine it with baseUrl -> projectRoot/generated/folder2/file3.ts.
  7. File exists. Done.

Virtual Directories with rootDirs#

Using 'rootDirs', you can inform the compiler of the roots making up this "virtual" directory; and thus the compiler can resolve relative modules imports within these "virtual" directories as if were merged together in one directory.

src
└── views
└── view1.ts (imports './template1')
└── view2.ts
generated
└── templates
└── views
└── template1.ts (imports './view2')

"rootDirs" specify a list of roots whose contents are expected to merge at run-time.

{
"compilerOptions": {
"rootDirs": [
"src/views",
"generated/templates/views"
]
}
}

Every time the compiler sees a relative module import in a subfolder of one of the rootDirs, it will attempt to look for this import in each of the entries of rootDirs.

The flexibility of rootDirs is not limited to specifying a list of physical source directories that are logically merged.
Consider an internationalization scenario where a build tool automatically generates locale specific bundles by interpolating a special path token, say #{locale}, as part of a relative module path such as ./#{locale}/messages. In this hypothetical setup the tool enumerates supported locales, mapping the abstracted path into ./zh/messages, ./de/messages, and so forth.

Assume that each of these modules exports an array of strings. For example ./zh/messages might contain:

export default [
"您好吗",
"很高兴认识你"
];

By leveraging rootDirs we can inform the compiler of this mapping and thereby allow it to safely resolve ./#{locale}/messages, even though the directory will never exist. For example, with the following tsconfig.json:

{
"compilerOptions": {
"rootDirs": [
"src/zh",
"src/de",
"src/#{locale}"
]
}
}

The compiler will now resolve import messages from './#{locale}/messages' to import messages from './zh/messages' for tooling purposes, allowing development in a locale agnostic manner without compromising design time support.

Tracing module resolution#

Invoking the compiler with --traceResolution

tsc --traceResolution

Results in an output such as:

======== Resolving module 'typescript' from 'src/app.ts'. ========
Module resolution kind is not specified, using 'NodeJs'.
Loading module 'typescript' from 'node_modules' folder.
File 'src/node_modules/typescript.ts' does not exist.
File 'src/node_modules/typescript.tsx' does not exist.
File 'src/node_modules/typescript.d.ts' does not exist.
File 'src/node_modules/typescript/package.json' does not exist.
File 'node_modules/typescript.ts' does not exist.
File 'node_modules/typescript.tsx' does not exist.
File 'node_modules/typescript.d.ts' does not exist.
Found 'package.json' at 'node_modules/typescript/package.json'.
'package.json' has 'types' field './lib/typescript.d.ts' that references 'node_modules/typescript/lib/typescript.d.ts'.
File 'node_modules/typescript/lib/typescript.d.ts' exist - use it as a module resolution result.
======== Module name 'typescript' was successfully resolved to 'node_modules/typescript/lib/typescript.d.ts'. ========

Using --noResolve#

Normally the compiler will attempt to resolve all module imports before it starts the compilation process. Every time it successfully resolves an import to a file, the file is added to the set of files the compiler will process later on.

The --noResolve compiler options instructs the compiler not to "add" any files to the compilation that were not passed on the command line. It will still try to resolve the module to files, but if the file is not specified, it will not be included.

For instance:

app.ts#

import * as A from "moduleA" // OK, 'moduleA' passed on the command-line
import * as B from "moduleB" // Error TS2307: Cannot find module 'moduleB'.
tsc app.ts moduleA.ts --noResolve

Compiling app.ts using --noResolve should result in:

  • Correctly finding moduleA as it was passed on the command-line.
  • Error for not finding moduleB as it was not passed.

Common Questions#

Why does a module in the exclude list still get picked up by the compiler?#

tsconfig.json turns a folder into a “project”. Without specifying any “exclude” or “files” entries, all files in the folder containing the tsconfig.json and all its sub-directories are included in your compilation. If you want to exclude some of the files use “exclude”, if you would rather specify all the files instead of letting the compiler look them up, use “files”.

That was tsconfig.json automatic inclusion. That does not embed module resolution as discussed above. If the compiler identified a file as a target of a module import, it will be included in the compilation regardless if it was excluded in the previous steps.

So to exclude a file from the compilation, you need to exclude it and all files that have an import or /// <reference path="..." /> directive to it.