This tutorial aims to guide you through the process of configuring module resolution and paths in TypeScript. This helps in controlling how your modules get loaded and aids in resolving potential issues with module importing.
By the end of this tutorial, you will be able to:
- Understand module resolution in TypeScript
- Configure module resolution and paths
- Resolve issues related to module importing
Module resolution is the process TypeScript uses to decide what an import statement refers to. There are two strategies of module resolution in TypeScript: Node and Classic.
The Node module resolution mimics the way the Node.js runtime attempts to resolve modules. The Classic resolution strategy was the original strategy TypeScript used.
To configure the module resolution strategy, add "moduleResolution": "node"
or "moduleResolution": "classic"
to your tsconfig.json
file.
{
"compilerOptions": {
"moduleResolution": "node"
}
}
Paths allow you to set aliases for your import statements. This is useful when your imports become too long. To configure paths, you can add the "paths" and "baseUrl" options in your tsconfig.json
file.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"utilities/*": ["src/utilities/*"]
}
}
}
Example 1: Using Node Module Resolution
{
"compilerOptions": {
"moduleResolution": "node"
}
}
When using Node module resolution, TypeScript will mimic Node.js runtime's way of resolving modules.
Example 2: Configuring Paths
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"utilities/*": ["src/utilities/*"]
}
}
}
In this example, we set the base URL to the current directory, and we set an alias for src/utilities
. Now, instead of writing import { myFunc } from '../../src/utilities/myFunc'
, you can write import { myFunc } from 'utilities/myFunc'
.
In this tutorial, we covered the process of module resolution and how to configure it in TypeScript. We also learned how to configure paths to simplify our import statements.
To continue learning, you can delve deeper into how TypeScript integrates with the Node.js module system or how to make use of path mapping in larger codebases.
tsconfig.json
:{
"compilerOptions": {
"moduleResolution": "node"
}
}
tsconfig.json
. Replace "utilities/*"
and ["src/utilities/*"]
with your directory and path:{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"utilities/*": ["src/utilities/*"]
}
}
}
After this, any time you want to import something from src/utilities
, you can use the utilities/
alias.