TypeScript Path Mapping paths
paths is a configuration option in tsconfig.json, used to configure module path aliases.
It makes import paths more concise while keeping the code structure organized and clear.
SVG Diagram: How Path Mapping Works
Why Path Mapping is Needed
As project size grows, the file directory structure gets deeper.
Using relative paths to import files (e.g., ../../../components/Button) makes the code hard to read and maintain.
Path mapping allows us to use aliases (e.g., @/components/Button) to replace lengthy relative paths.
Alias:Path aliases make import paths more concise and make it easier to adjust the project structure.
Basic Configuration
Configure paths and baseUrl in tsconfig.json.
tsconfig.json
"compilerOptions": {
// Base path: the root directory for all path aliases
"baseUrl": ".",
// Path mapping configuration
"paths": {
// Alias starting with @/, pointing to the src directory
"@/*": ["src/*"],
// Alias starting with @components
"@components/*": ["src/components/*"],
// Alias starting with @utils
"@utils/*": ["src/utils/*"],
// Alias starting with @services
"@services/*": ["src/services/*"],
// Alias starting with @assets
"@assets/*": ["src/assets/*"],
// Alias starting with @types
"@types/*": ["src/types/*"]
}
}
}
baseUrl:After setting baseUrl, paths in the paths option will be resolved relative to this directory.
Using Path Aliases
After configuration is complete, you can use aliases to import modules in your code.
src/components/Button.tsx
import { Button } from '@/components/Button';
import { User } from '@types/user';
import { fetchUser } from '@services/userApi';
import { formatDate } from '@utils/date';
// Import styles
import styles from '@/components/Button.module.css';
// Import images
import logo from '@assets/logo.png';
// Use the imported module
const handleClick = () => {
console.log('Button clicked');
};
const userButton = new Button({
text: 'User',
onClick: handleClick
});
console.log('Component loaded successfully');
Syntax:Use * as a wildcard in the paths configuration, and match the actual path with * when importing.
Webpack Alias Configuration
If using Webpack, you also need to configure resolve.alias to support runtime.
webpack.config.js
const path = require('path');
// Webpack configuration
module.exports = {
// Other configuration...
resolve: {
// Path alias configuration, needs to stay consistent with tsconfig.json
alias: {
// Alias starting with @
'@': path.resolve(__dirname, 'src'),
// Other aliases
'@components': path.resolve(__dirname, 'src/components'),
'@utils': path.resolve(__dirname, 'src/utils'),
'@services': path.resolve(__dirname, 'src/services'),
'@types': path.resolve(__dirname, 'src/types'),
'@assets': path.resolve(__dirname, 'src/assets')
},
// File extensions
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
}
};
Runtime consistency:Webpack's alias configuration must be consistent with TypeScript's paths configuration, otherwise a module not found error will occur at runtime.
Vite Configuration
When using Vite, you need to configure both tsconfig.json and vite.config.ts.
vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
// Vite configuration
export default defineConfig({
plugins: [react()],
// Path alias configuration
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@utils': path.resolve(__dirname, './src/utils'),
'@services': path.resolve(__dirname, './src/services'),
'@types': path.resolve(__dirname, './src/types'),
'@assets': path.resolve(__dirname, './src/assets')
}
}
});
Vite:Vite uses Rollup as its bundling engine, so you need to configure aliases in resolve.alias.
Multi-Project Path Configuration
In Monorepo projects, you can configure cross-package path aliases.
tsconfig.json (Monorepo)
"compilerOptions": {
// Base path
"baseUrl": ".",
// Path mapping, supports cross-package references
"paths": {
// Reference modules from the current package
"@/*": ["src/*"],
// Reference modules from other packages
"@my-ui/button": ["packages/ui-button/src/index.ts"],
"@my-ui/modal": ["packages/ui-modal/src/index.ts"],
"@my-utils/date": ["packages/utils-date/src/index.ts"],
"@my-hooks/useFetch": ["packages/hooks-use-fetch/src/index.ts"]
}
}
}
Monorepo:In Monorepo projects, paths can reference source paths of other packages.
Notes
- baseUrl is required:paths must be used together with baseUrl
- Wildcard matching:Use * to match any path
- Keep consistent:Webpack/Vite configuration must stay consistent with tsconfig
- Relative paths:Paths in the paths option are relative to baseUrl
Best practices:Using path aliases can make code more concise, but don't overuse them; it's recommended to unify naming conventions.
Summary
Path mapping is an important tool for managing import paths in TypeScript projects.
- paths:Configure path aliases
- baseUrl:Set the base path
- Wildcard:Use * to match any characters
- Build tools:Webpack/Vite need synchronized configuration
Other ExtensionsRecommendation:Set path aliases for commonly used directories to improve code readability and maintainability.