前置知识: TypeScript

模块解析策略

1 minIntermediate2026/6/14

TypeScript模块解析与路径映射

1. 模块解析策略

// tsconfig.json
{
  "compilerOptions": {
    "moduleResolution": "bundler" // "node" | "nodenext" | "bundler"
  }
}
策略说明
nodeNode.js 经典解析
nodenextNode.js ESM 解析
bundler现代打包工具解析

2. 路径映射

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"],
      "@utils/*": ["src/utils/*"]
    }
  }
}
import { Button } from '@components/Button';
import { formatDate } from '@utils/date';

3. 模块导出

// 命名导出
export const name = 'Alice';
export function greet() {}

// 默认导出
export default class App {}

// 重导出
export { Button } from './Button';
export * from './utils';

// 类型导出
export type { User } from './types';

4. 命名空间

namespace Utils {
  export function formatDate(d: Date): string {
    return d.toISOString();
  }
  export const VERSION = '1.0.0';
}

Utils.formatDate(new Date());