Modules in TypeScript are a way to organize and encapsulate code into reusable and maintainable chunks. They allow you to split your code into separate files and then import/export functionalities between them. This makes the code easier to manage, especially in large projects. Here’s a detailed overview of how to work with modules in TypeScript:
Creating and Exporting Modules
In TypeScript, you can create a module by simply writing some code in a .ts
file and exporting what you want to be accessible from other modules.
Named Exports
Named exports allow you to export multiple bindings from a module. Each export must be explicitly named.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
Default Exports
A default export can be a function, class, object, or anything else. There can only be one default export per module.
// logger.ts
export default function log(message: string): void {
console.log(message);
}
Importing Modules
You can import modules using the import
statement.
Importing Named Exports
To import named exports, you use curly braces to specify the names of the exports you want to import.
// app.ts
import { add, subtract } from './math';
console.log(add(5, 3)); // Outputs: 8
console.log(subtract(5, 3)); // Outputs: 2
Importing Default Exports
To import a default export, you don’t use curly braces.
// app.ts
import log from './logger';
log('Hello, world!'); // Outputs: Hello, world!
Aliases
You can use aliases when importing to avoid name conflicts or to make names clearer.
// app.ts
import { add as addition, subtract as subtraction } from './math';
console.log(addition(5, 3)); // Outputs: 8
console.log(subtraction(5, 3)); // Outputs: 2
Re-exporting Modules
You can re-export modules, which is useful for creating a single entry point for multiple modules.
// index.ts
export { add, subtract } from './math';
export { default as log } from './logger';
Now you can import everything from index.ts
instead of importing from individual modules.
// app.ts
import { add, subtract, log } from './index';
console.log(add(5, 3)); // Outputs: 8
console.log(subtract(5, 3)); // Outputs: 2
log('Hello, world!'); // Outputs: Hello, world!