As your TypeScript projects grow in size and complexity, it becomes essential to organize your codebase into manageable pieces. Modules are a fundamental feature of TypeScript that help you achieve this by allowing you to split your code into separate files and then combine them as needed. In this tutorial, we'll explore how to use modules effectively to keep your code clean, maintainable, and scalable.
In TypeScript (and JavaScript), a module is simply a file containing declarations and statements that can be imported from other files. Modules help you encapsulate functionality, promote reusability, and avoid naming conflicts by providing a way to define private and public interfaces.
export keyword.import statement.Let's dive into some practical examples to understand how modules work in TypeScript.
Suppose you have a file math.ts that contains utility functions for basic arithmetic operations:
1// math.ts2export function add(a: number, b: number): number {3return a + b;4}56export function subtract(a: number, b: number): number {7return a - b;8}
You can then import these functions in another file, say app.ts:
1// app.ts2import { add, subtract } from './math';34console.log(add(5, 3)); // Output: 85console.log(subtract(5, 3)); // Output: 2
A module can have one default export. This is useful when you want to export a single primary entity from the module.
1// calculator.ts2const PI = 3.14;34export default {5add,6subtract,7multiply(a: number, b: number): number {8return a * b;9},10divide(a: number, b: number): number {11if (b === 0) throw new Error("Cannot divide by zero");12return a / b;13}14};
You can import the default export using any name:
1// app.ts2import Calculator from './calculator';34console.log(Calculator.add(5, 3)); // Output: 85console.log(Calculator.subtract(5, 3)); // Output: 26console.log(Calculator.multiply(5, 3)); // Output: 157console.log(Calculator.divide(5, 3)); // Output: 1.666...
If a module has many exports and you want to import them all into a single namespace, you can use the * as syntax:
1// utils.ts2export function log(message: string): void {3console.log(message);4}56export function warn(message: string): void {7console.warn(message);8}
You can import all exports from utils.ts into a namespace called Utils:
1// app.ts2import * as Utils from './utils';34Utils.log('This is a log message');5Utils.warn('This is a warning message');
In the next section, we'll explore Namespaces, another way to organize code in TypeScript. Namespaces provide a way to group related functionality and help avoid naming conflicts by creating a scope for your declarations.
Stay tuned!