In TypeScript, modules are a way of organizing code into reusable units. They provide a mechanism for encapsulating and exporting functionality, making it easier to manage large codebases and promote modularity and code reuse. TypeScript supports various module formats, including CommonJS, AMD, UMD, ES6 Modules, and more.
1. Defining Modules:
You can create a module by simply placing your code inside a TypeScript file and using the export
keyword to expose functions, classes, variables, or other entities outside the module.
// math.ts export function add(a: number, b: number): number { return a + b; } export function subtract(a: number, b: number): number { return a - b; }
2. Importing Modules:
To use functionality from a module in another file, you can use the import
keyword followed by the module path and the name of the exported entity.
// app.ts import { add, subtract } from './math'; console.log(add(5, 3)); // Output: 8 console.log(subtract(10, 4)); // Output: 6
3. Default Exports:
In addition to named exports, TypeScript also supports default exports, where you export a single entity as the default export from a module.
// utils.ts
export default function greet(name: string): string {
return `Hello, ${name}!`;
}
// app.ts import greet from './utils'; console.log(greet('John')); // Output: Hello, John!
4. Re-Exporting Modules:
You can re-export functionality from one module in another module using the export ... from ...
syntax.
// utils.ts export function greet(name: string): string { return `Hello, ${name}!`; }
5. Module Resolution:
TypeScript uses a module resolution strategy to find and load modules based on import statements. It follows a set of rules to locate modules relative to the importing file or by searching specified module paths.
6. Module Formats:
TypeScript supports various module formats, including CommonJS, AMD, UMD, and ES6 Modules. You can specify the target module format using the --module
compiler option or by configuring it in the tsconfig.json
file.
{ "compilerOptions": { "module": "commonjs" } }
7. Namespace (Legacy):
TypeScript also supports namespaces, which are a way of organizing code into logical groups. However, namespaces are considered legacy and are not recommended for modern TypeScript projects. It's generally preferable to use ES6 modules for organizing code.
// utils.ts namespace MathUtils { export function add(a: number, b: number): number { return a + b; } } // app.ts import { MathUtils } from './utils'; console.log(MathUtils.add(5, 3)); // Output: 8
Conclusion:
Modules in TypeScript provide a powerful mechanism for organizing and reusing code in applications. Whether using named exports, default exports, or re-exporting modules, TypeScript's module system helps developers build modular, maintainable, and scalable applications. Understanding module syntax and best practices is essential for effective TypeScript development.
0 Comments