Z
ZHANK
模块与配置

模块与命名空间

掌握 ES 模块导入导出、namespace 命名空间

模块与命名空间

TypeScript 支持 ES 模块和传统的命名空间两种组织方式。

学完本章你将: 掌握模块导入导出、namespace、模块解析。


ES 模块

typescript
// math.ts —— 导出
export function add(a: number, b: number): number { return a + b; }
export const PI = 3.14159;
export default function multiply(a: number, b: number): number { return a * b; }

// app.ts —— 导入
import multiply, { add, PI } from "./math";
console.log(add(1, 2));     // 3
console.log(multiply(3, 4)); // 12

// 类型导出
export type { User } from "./models";

命名空间

typescript
// 传统命名空间(不推荐用于新项目)
namespace Validation {
    export interface StringValidator {
        isValid(s: string): boolean;
    }

    export class EmailValidator implements StringValidator {
        isValid(s: string): boolean {
            return s.includes("@");
        }
    }
}

const validator = new Validation.EmailValidator();
console.log(validator.isValid("a@b.com")); // true

// 跨文件命名空间
/// <reference path="./Validation.ts" />

import type

typescript
// 仅导入类型(编译时移除)
import type { User, Post } from "./models";

// 混合导入
import { type User, createUser } from "./models";

// 动态导入
async function loadModule() {
    const { Chart } = await import("./chart");
    return new Chart();
}

模块解析策略

typescript
// tsconfig.json
{
    "compilerOptions": {
        "moduleResolution": "bundler", // 推荐
        // 或 "node16" / "nodenext"
        "baseUrl": ".",
        "paths": {
            "@/*": ["src/*"],
            "@utils/*": ["src/utils/*"]
        }
    }
}
typescript
// 使用路径别名
import { formatDate } from "@utils/date";
import { Button } from "@/components/Button";