baseUrl and paths for Custom Mappings
What You'll Learn
You'll learn how to configure path aliases in TypeScript to avoid deep, brittle relative imports like ../../../utils and make your imports cleaner and more maintainable.
The Problem with Deep Relative Imports
Imagine you're working in a large project and need to import a utility function:
import { formatDate } from '../../../shared/utils/formatters';
This import is fragile. If you move the file, you need to recount the ../ segments. It's also hard to read — you have to mentally trace up the directory tree.
Now imagine every file has imports like this. Your codebase becomes a maze of relative path puzzles.
What baseUrl and paths Do
TypeScript's baseUrl and paths options let you define path aliases — shorthand names for directories or modules that TypeScript resolves automatically.
Instead of:
import { formatDate } from '../../../shared/utils/formatters';
You can write:
import { formatDate } from '@utils/formatters';
TypeScript knows where @utils points, and you never have to count ../ again.
How It Works
In tsconfig.json:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@utils/*": ["shared/utils/*"],
"@components/*": ["ui/components/*"]
}
}
}
- baseUrl: The root directory for all non-relative imports. Paths are resolved relative to this.
- paths: Maps alias patterns (like
@utils/*) to actual file paths (likeshared/utils/*).
The * acts as a wildcard, matching any file or subfolder.
Why This Matters
Before:
- Imports break when you refactor file structure.
- Deep nesting makes code hard to read.
- Onboarding requires memorizing directory hierarchies.
After:
- Imports stay consistent regardless of file location.
- Aliases communicate intent (e.g.,
@models,@services). - Refactoring becomes safer and faster.
Important Note
Path aliases only affect TypeScript's type checking. At runtime, Node.js or your bundler (like Webpack or Vite) won't understand them automatically. You'll need to configure your build tool separately — but that's a tooling concern, not a TypeScript concern.
Key Takeaway:
Use baseUrl and paths to replace brittle relative imports with readable, refactor-safe path aliases that clarify your project's structure.