YouTip LogoYouTip

Ts Paths

TypeScript Path Mapping paths


Why Path Mapping Is Needed

As project scale grows, file directory structures become increasingly deep.

Using relative paths to import files (e.g., ../../../components/Button) makes code hard to read and maintain.

Path mapping allows us to use aliases (e.g., @/components/Button) instead of lengthy relative paths.

Alias: Path aliases make import paths more concise and facilitate restructuring the project.

Basic Configuration

Configure paths and baseUrl in tsconfig.json.

{
  "compilerOptions": {
    // Base path: root directory for all path aliases
    "baseUrl": ".",
    // Path mapping configuration
    "paths": {
      // Alias starting with @/, pointing to 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 paths are resolved relative to this directory.

Using Path Aliases

After configuration, you can use aliases to import modules in your code.

// src/components/Button.tsx

// Import using path aliases
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 imported modules
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 paths configuration; during import, * matches the actual path.

Webpack Alias Configuration

If using Webpack, you also need to configure resolve.alias for runtime support.

// Import webpack module
const path = require('path');

// Webpack configuration
module.exports = {
  // Other configurations...
  resolve: {
    // Path alias configuration, must match 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 match TypeScript’s paths configuration; otherwise, runtime errors like β€œmodule not found” will occur.

Vite Configuration

When using Vite, configure both tsconfig.json and vite.config.ts.

// Import Vite module
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 bundler and requires alias configuration in resolve.alias.

Multi-Project Path Configuration

In Monorepo projects, you can configure cross-package path aliases.

{
  "compilerOptions": {
    // Base path
    "baseUrl": ".",
    // Path mapping, supporting cross-package references
    "paths": {
      // Reference modules in the current package
      "@/*": ["src/*"],
      // Reference modules in 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 code paths from other packages.

Notes

  • baseUrl is required: paths must be used together with baseUrl
  • Wildcard matching: Use * to match any path segment
  • Consistency: Webpack/Vite configurations must match tsconfig.json
  • Relative paths: Paths in paths are relative to baseUrl
Best practice: Path aliases make code more concise, but avoid overuseβ€”prefer a unified naming convention.

Summary

Path mapping is an essential tool for managing import paths in TypeScript projects.

  • paths: Configure path aliases
  • baseUrl: Set the base directory
  • Wildcard: Use * to match any characters
  • Build tools: Webpack/Vite require synchronized configuration
Suggestion: Define path aliases for commonly used directories to improve code readability and maintainability.
← Ts MonorepoTs Recursive Types β†’