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
{
"compilerOptions": {
"baseUrl": "./modules"
}
}
Now imports to "moduleA"
would be looked up in ./modules/moduleA
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"
.
{
"compilerOptions": {
"baseUrl": "./node_modules",
"paths": {
"jquery": ["jquery/dist/jquery.slim.min"]
}
}
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:
src
└── views
└── view1.ts (imports './template1')
└── view2.ts
generated
└── templates
└── views
└── 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:
{
"compilerOptions": {
"rootDirs": [
"src/views",
"generated/templates/views"
]
}
}
Tracing module resolution
—traceResolution
offers a handy way to understand how modules have been resolved by the compiler.
tsc --traceResolution