在 TypeScript 中,模块化是一种将代码分割成独立单元的方式,每个单元可以封装特定的功能或数据。模块化有助于保持代码的组织性、可维护性和可重用性。TypeScript 支持 ES6 模块标准,这意味着你可以使用
import
和export
语句来创建模块。
TS快速入门-模块化
导出模块成员
使用 export
关键字可以将类、接口、类型、函数或变量导出,以便它们可以在其他文件中被导入。
// myModule.ts
export class Calculator {
private value: number = 0;
public add(x: number): void {
this.value += x;
}
public getValue(): number {
return this.value;
}
}
// 或者使用 '*' 来导出所有
export * from './someModule';
导入模块成员
使用 import
关键字可以从其他文件导入导出的成员。
// app.ts
import { Calculator } from './myModule';
let calc = new Calculator();
calc.add(10);
console.log(calc.getValue()); // 输出 10
重命名导入和导出
在导入或导出时,你可以使用 as
关键字来重命名模块成员。
// myModule.ts
export class SomeUtility {
// ...
}
// app.ts
import { SomeUtility as Utility } from './myModule';
let util = new Utility();
默认导出
每个模块可以有一个默认导出,这使得导入时不需要使用花括号。
// myDefaultModule.ts
export default class DefaultClass {
// ...
}
// app.ts
import DefaultImportedClass from './myDefaultModule';
let defaultInstance = new DefaultImportedClass();
模块解析
TypeScript 支持不同的模块解析策略,如 CommonJS
、AMD
等,但默认使用 ES6 模块解析。
// 使用相对路径或绝对路径导入
import SomeClass from './someClass';
import SomeOtherClass from '/path/to/someOtherClass';
模块化示例
以下是一个模块化的示例,展示了如何在 TypeScript 中创建和使用模块:
// calculator.ts
export class Calculator {
private value: number = 0;
public add(x: number): void {
this.value += x;
}
public subtract(x: number): void {
this.value -= x;
}
public getValue(): number {
return this.value;
}
}
// shape.ts
export interface Shape {
area(): number;
}
// circle.ts
import { Shape } from './shape';
export class Circle implements Shape {
private radius: number;
constructor(radius: number) {
this.radius = radius;
}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
// app.ts
import { Calculator } from './calculator';
import { Circle } from './circle';
let calc = new Calculator();
calc.add(5);
calc.subtract(3);
console.log(calc.getValue()); // 输出 2
let circle = new Circle(10);
console.log(circle.area()); // 输出 314.159...
TypeScript 中模块化的基本用法,包括如何导出和导入模块成员、如何使用默认导出和重命名导入/导出。模块化是现代 JavaScript 和 TypeScript 开发中的核心概念,它有助于构建大型、可维护的应用程序。