Modules in TypeScript are a way to organize and encapsulate code, allowing you to split your code into smaller, more manageable pieces. They help in maintaining large-scale projects by keeping each part of the code in separate files and exposing only the necessary parts to the rest of the application. They promote code reusability, maintainability, and keep the global scope clean, preventing naming conflicts.
In TypeScript, a module is a file containing statements and declarations, which can export or import values from other modules. There are two main types of modules in TypeScript: namespace modules (or internal modules) and external modules.
1. Namespace Modules:
These were previously called "internal modules" but are now called "namespaces.". They use the ‘namespace‘ keyword to create a single, top-level module with multiple nested modules inside.
namespace MyNamespace {
export class MyClass {
constructor() {
console.log("Hello from MyClass in MyNamespace");
}
}
}
let example = new MyNamespace.MyClass();
Namespace modules are not commonly used nowadays, as they have been mostly replaced by external modules when working with modern module bundlers.
2. External Modules:
External modules are the most common way to work with modules in TypeScript. These are simply regular TypeScript files that use the ‘import‘ and ‘export‘ keywords to share code between files. The module format is determined by the ‘module‘ setting in the ‘tsconfig.json‘ file (e.g., CommonJS, ES2015, AMD, System). Here’s an example:
‘math.ts‘:
export function add(a: number, b: number): number {
return a + b;
}
‘main.ts‘:
import { add } from "./math";
console.log(add(1, 2));
In this example, the ‘add‘ function is exported from the ‘math.ts‘ file and then imported into the ‘main.ts‘ file. The code stays organized by keeping related functions and classes in separate files.
To summarize, TypeScript modules provide a way to organize your code in a clean and structured manner, making it easier to maintain and share between different parts of your application. They prevent naming conflicts and ensure code reusability.