TypeScript中的模块是什么?
- 1. 模块的基本概念
- 1.1 使用模块
- 2. 默认导出 vs 命名导出
- 2.1 默认导出
- 2.2 命名导出
- 3. 模块的作用域
- 4. 模块的声明与引用
在现代软件开发中,模块化是构建大型、可维护应用程序的关键概念。TypeScript,作为JavaScript的一个超集,引入了静态类型系统和对ES6模块的原生支持,使得在大型项目中管理复杂性变得更加容易。在
1. 模块的基本概念
在TypeScript中,模块是一种封装代码的方式,允许你将功能分割成独立、可重用的单元。每个模块可以包含变量、函数、类等,并且可以控制对这些实体的访问权限。
// myModule.ts
export function greet(name: string): string {
return `Hello, ${name}!`;
}
export const pi: number = 3.14;
在这个例子中,我们创建了一个名为myModule.ts的模块,它导出了greet函数和pi常量。
1.1 使用模块
// app.ts
import { greet, pi } from './myModule';
console.log(greet('TypeScript')); // 输出: Hello, TypeScript!
console.log(pi); // 输出: 3.14
在app.ts中,我们通过import语句从myModule中导入了greet函数和pi常量,并使用它们。
2. 默认导出 vs 命名导出
TypeScript支持两种导出方式:默认导出和命名导出。
2.1 默认导出
默认导出允许你从一个模块中导出一个单一的主要实体。
// defaultExport.ts
export default class Calculator {
add(x: number, y: number): number {
return x + y;
}
}
使用默认导出时,导入时不需要使用大括号:
// app.ts
import calculator from './defaultExport';
const result = calculator.add(1, 2);
console.log(result); // 输出: 3
2.2 命名导出
命名导出允许你从模块中导出多个实体,并且每个实体都有一个唯一的名称。
// namedExport.ts
export function square(x: number): number {
return x * x;
}
export class Circle {
constructor(public radius: number) {}
getArea(): number {
return Math.PI * this.radius * this.radius;
}
}
使用命名导出时,导入时需要使用大括号:
// app.ts
import { square, Circle } from './namedExport';
const area = square(5);
const circle = new Circle(10);
console.log(area); // 输出: 25
console.log(circle.getArea()); // 输出: 314 (approximately)
3. 模块的作用域
模块内部定义的变量和函数默认是局部的,对其他模块是不可见的。这有助于避免命名冲突,并提高代码的封装性。
// utils.ts
let counter = 0;
export function increment(): number {
return ++counter;
}
在这个模块中,counter变量是局部的,只能在utils.ts内部访问和修改。
4. 模块的声明与引用
在TypeScript中,你可以通过声明模块来引用其他模块。这允许TypeScript编译器检查类型错误。
// myModule.ts
export class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
greet() {
return `Hello, my name is ${this.name}!`;
}
}
// app.ts
import { Animal } from './myModule';
let animal = new Animal('Goat');
console.log(animal.greet()); // 输出: Hello, my name is Goat!
在这个例子中,我们声明了对myModule的引用,并导入了Animal类。