模块

模块是 TypeScript 组织代码的重要方式。通过模块,可以将代码分割成独立的功能单元,实现代码的封装、复用和维护。TypeScript 使用 ES6 模块系统,支持 exportimport 语法。

什么是模块

模块是一个独立的文件,包含相关的代码。模块内部的变量、函数、类等默认是私有的,只有通过 export 导出才能被其他模块访问。

export const name = "张三"

export function greet(name: string): string {
  return `你好,${name}`
}

export class User {
  constructor(public name: string) {}
}

每个文件都是一个模块,导出的内容可以被其他模块导入使用。

模块的优势

模块化开发有很多优势:

  • 封装:模块内部的实现细节对外隐藏
  • 复用:模块可以在多个项目中复用
  • 维护:模块独立,便于维护和测试
  • 命名空间:避免全局变量污染

模块导出

使用 export 关键字导出模块成员。

export const PI = 3.14159

export function add(a: number, b: number): number {
  return a + b
}

export class Calculator {
  add(a: number, b: number): number {
    return a + b
  }
}

导出的成员可以是变量、函数、类、接口、类型别名等。

模块导入

使用 import 关键字导入模块成员。

import { PI, add, Calculator } from "./math"

console.log(PI)
console.log(add(1, 2))

const calc = new Calculator()
console.log(calc.add(3, 4))

导入时可以重命名、导入全部、默认导入等。

默认导出

每个模块可以有一个默认导出。

export default class User {
  constructor(public name: string) {}
}

默认导出导入时可以自定义名称。

import User from "./user"

const user = new User("张三")

模块解析

TypeScript 支持两种模块解析策略:Classic 和 Node。Classic 是 TypeScript 的默认策略,Node 模拟 Node.js 的模块解析机制。

{
  "compilerOptions": {
    "moduleResolution": "node"
  }
}

Node 策略更常用,支持 node_modules 查找和路径映射。

模块格式

TypeScript 支持多种模块格式:

  • ES6:使用 importexport
  • CommonJS:使用 requiremodule.exports
  • AMD:异步模块定义
  • UMD:通用模块定义
{
  "compilerOptions": {
    "module": "ESNext"
  }
}

ES6 模块是现代 JavaScript 的标准,推荐使用。

实际应用

模块在实际开发中常用于组织功能代码。

export interface User {
  id: number
  name: string
  email: string
}

export function validateUser(user: User): boolean {
  return user.name.length > 0 && user.email.includes("@")
}

export async function fetchUser(id: number): Promise<User> {
  return {
    id,
    name: "张三",
    email: "zhangsan@example.com"
  }
}

模块让代码结构清晰,便于团队协作。

小结

模块是 TypeScript 组织代码的重要方式,使用 exportimport 语法。模块提供封装、复用、维护和命名空间隔离等优势。每个模块可以有一个默认导出,多个命名导出。TypeScript 支持多种模块格式和解析策略。合理使用模块可以提高代码的可维护性和可复用性。