Module resolution enhancements: BaseUrl, Path mapping, rootDirs and tracing

TypeScript 2.0 provides a set of additional module resolution knops to inform the compiler where to find declarations for a given module.

See Module Resolution documentation for more details.

Base URL

Using a baseUrl is a common practice in applications using AMD module loaders where modules are “deployed” to a single folder at run-time.All module imports with non-relative names are assumed to be relative to the baseUrl.

Example

  1. {
  2. "compilerOptions": {
  3. "baseUrl": "./modules"
  4. }
  5. }

Now imports to "moduleA" would be looked up in ./modules/moduleA

  1. import A from "moduleA";

Path mapping

Sometimes modules are not directly located under baseUrl.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.

Example

For instance, an import to a module "jquery" would be translated at runtime to "node_modules/jquery/dist/jquery.slim.min.js".

  1. {
  2. "compilerOptions": {
  3. "baseUrl": "./node_modules",
  4. "paths": {
  5. "jquery": ["jquery/dist/jquery.slim.min"]
  6. }
  7. }

Using "paths" also allow 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.

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.

Example

Given this project structure:

  1. src
  2. └── views
  3. └── view1.ts (imports './template1')
  4. └── view2.ts
  5. generated
  6. └── templates
  7. └── views
  8. └── template1.ts (imports './view2')

A build step will copy the files in /src/views and /generated/templates/views to the same directory in the output.At run-time, a view can expect its template to exist next to it, and thus should import it using a relative name as "./template".

"rootDirs" specify a list of roots whose contents are expected to merge at run-time.So following our example, the tsconfig.json file should look like:

  1. {
  2. "compilerOptions": {
  3. "rootDirs": [
  4. "src/views",
  5. "generated/templates/views"
  6. ]
  7. }
  8. }

Tracing module resolution

—traceResolution offers a handy way to understand how modules have been resolved by the compiler.

  1. tsc --traceResolution