How does path mapping via the 'paths' compiler option let you use cleaner, absolute-style import paths?
Short answer
The 'paths' option (used together with 'baseUrl') lets you define custom import aliases (like '@/components/*') that TypeScript resolves during type-checking — though note the bundler or runtime (Webpack, Vite, ts-node, Node itself) must be separately configured to understand…
Advertisement
AModel answer
The 'paths' option (used together with 'baseUrl') lets you define custom import aliases (like '@/components/*') that TypeScript resolves during type-checking — though note the bundler or runtime (Webpack, Vite, ts-node, Node itself) must be separately configured to understand the same aliases at build/run time, since TypeScript's path mapping is a compile-time-only convenience.
// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "@components/*": ["src/components/*"] }
}
}
// usage.ts
import Button from '@components/Button'; // instead of '../../../components/Button'Real-world example
Avoiding long, fragile relative import chains like '../../../../components/Button' in a deeply nested project structure.
Likely follow-ups
- Why doesn't configuring 'paths' alone make the aliases work at runtime in a plain Node.js script?
Related topics