TypeScript Paths Mapping
Paths mapping gives an import name a folder address inside the project. The baseUrl setting anchors the map, and each paths entry links a name pattern to one or more folders.
A tsconfig with a paths map
The config anchors the map at the project root and sends every @lib name into the lib folder. The closing example of this lesson is compiled by this file as a small project.
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"strict": true,
"outDir": "out",
"baseUrl": ".",
"paths": {
"@lib/*": ["./lib/*"]
}
}
}The lib/shapes.ts file
The library file holds a Shape type and a describeShape function. It lives in the folder the alias points to.
export interface Shape {
kind: string;
size: number;
}
export function describeShape(shape: Shape): string {
return shape.kind + ' of size ' + shape.size;
}One alias, several folders
A paths entry can list fallback folders in order. The compiler tries each folder until the name resolves.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@lib/*": ["./lib/*", "./shared/*"]
}
}
}Example
import type { Shape } from '@lib/shapes';
import { describeShape } from './lib/shapes';
const card: Shape = { kind: 'square', size: 4 };
console.log(describeShape(card));Key points
- The baseUrl setting names the root folder that the paths map is resolved against.
- A paths entry maps a pattern such as @lib/* to a folder pattern such as ./lib/*.
- Type-only imports can travel by alias safely, because they are erased from the emitted JavaScript.
- Runtime imports in this lesson stay relative, so the emitted files resolve under plain Node.
In this example, the Shape type arrives through the @lib alias and is erased, while the function import stays relative so the emitted JavaScript runs under Node.
Note
The compiler does not rewrite paths in emitted JavaScript, so a bundler or loader resolves aliases at runtime in real projects.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
What happens to a paths alias in the emitted JavaScript?