patterntypescriptnoneModerate
tsconfig paths Aliases for Clean Imports
Viewed 0 times
TypeScript 2.0+
tsconfig pathsimport aliasbaseUrlmodule resolutionpath mapping
Error Messages
Problem
Deep relative imports like '../../../../utils/helpers' are fragile, hard to read, and break when files are moved.
Solution
Configure 'paths' in tsconfig.json to create import aliases, then mirror them in your bundler config.
// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@utils/*": ["./src/utils/*"],
"@components/*": ["./src/components/*"]
}
}
}// Now instead of:
import { formatDate } from '../../../../utils/date';
// Use:
import { formatDate } from '@utils/date';// vite.config.ts — must mirror paths
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-plugin-tsconfig-paths';
export default defineConfig({ plugins: [tsconfigPaths()] });Why
tsconfig 'paths' only affects TypeScript's type resolution, not the actual module bundling. Both the TypeScript compiler and the bundler/runtime must be configured separately.
Gotchas
- tsconfig paths do NOT work at runtime — Node.js, Jest, Vite, and Webpack all need separate alias configuration.
- For Jest: use 'moduleNameMapper' in jest.config. For Node.js: use tsconfig-paths or tsx.
- baseUrl must be set for paths to work.
Revisions (0)
No revisions yet.