在 TypeScript 中,模块是一种用于组织和封装代码的机制。模块帮助开发者将代码拆分成可重用的单元,并提供了命名空间、依赖管理和代码组织的工具。以下是 TypeScript 中模块的基本概念和用法:

导出和导入:

1. 导出变量、函数和类:
   使用 export 关键字可以将变量、函数和类导出,使其在其他模块中可用。
   // utils.ts
   export const PI = 3.14;

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

   export class Calculator {
       multiply(a: number, b: number): number {
           return a * b;
       }
   }

2. 导入变量、函数和类:
   使用 import 关键字可以在其他模块中导入变量、函数和类。
   // app.ts
   import { PI, add, Calculator } from './utils';

   console.log(PI); // 输出: 3.14

   const sum = add(10, 5);
   console.log(sum); // 输出: 15

   const calculator = new Calculator();
   console.log(calculator.multiply(3, 4)); // 输出: 12

3. 导出和导入默认:
   一个模块可以导出一个默认值,并且可以使用 default 关键字进行导入。
   // utils.ts
   const defaultExport = 42;
   export default defaultExport;
   // app.ts
   import myDefault from './utils';

   console.log(myDefault); // 输出: 42

命名空间:

1. 定义命名空间:
   使用 namespace 关键字可以创建一个命名空间。
   // math.ts
   namespace MathOperations {
       export function add(a: number, b: number): number {
           return a + b;
       }

       export function subtract(a: number, b: number): number {
           return a - b;
       }
   }

2. 使用命名空间:
   使用 /// <reference> 指令可以引用其他文件中的命名空间。
   /// <reference path="math.ts" />

   // app.ts
   let sum = MathOperations.add(10, 5);
   console.log(sum); // 输出: 15

模块的整体导入:

1. 整体导入:
   使用 import * as alias 可以将一个模块的所有导出绑定到一个别名上。
   // utils.ts
   export const PI = 3.14;
   export function add(a: number, b: number): number {
       return a + b;
   }
   // app.ts
   import * as utils from './utils';

   console.log(utils.PI); // 输出: 3.14
   console.log(utils.add(10, 5)); // 输出: 15

模块解析:

1. 相对路径和非相对路径:
   TypeScript 使用相对路径或非相对路径来解析模块。
   // 相对路径
   import { example } from './path/to/module';

   // 非相对路径
   import { example } from 'module';

2. 模块解析策略:
   TypeScript 支持多种模块解析策略,包括经典模块解析、Node.js 解析、以及逐渐引入的 ES6 解析。
   // tsconfig.json
   {
       "compilerOptions": {
           "module": "commonjs", // 使用 Node.js 解析
           // 或
           // "module": "esnext", // 使用 ES6 解析
           // ...
       }
   }

这些是 TypeScript 中模块的基本概念和用法。模块化是现代软件开发中的一个关键概念,有助于组织和管理代码,提高可维护性和可复用性。


转载请注明出处:http://www.pingtaimeng.com/article/detail/4705/TypeScript