TypeScript Modules
Modules in TypeScript help you organize your code into reusable pieces. They allow you to split your code into multiple files, making it easier to maintain and scale your applications.
Exporting and Importing Modules
Use the export
keyword to make classes, functions, or variables available to other modules, and the import
keyword to use them in another file.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
// app.ts
import { add, subtract } from './math';
console.log(add(2, 3)); // Output: 5
console.log(subtract(5, 3)); // Output: 2
Default Exports
A module can have a default export, which can be imported without curly braces. This is useful when a module primarily exports a single functionality.
// math.ts
export default function multiply(a: number, b: number): number {
return a * b;
}
// app.ts
import multiply from './math';
console.log(multiply(2, 3)); // Output: 6
Re-exporting Modules
You can re-export modules to create a single entry point for multiple modules. This is useful for organizing large codebases.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
// index.ts
export { add, subtract } from './math';
// app.ts
import { add, subtract } from './index';
console.log(add(2, 3)); // Output: 5
console.log(subtract(5, 3)); // Output: 2
Using External Modules
You can use external modules from npm by importing them. TypeScript supports both CommonJS and ES modules.
// Using an external module (e.g., Express.js)
import express from 'express';
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Namespace Imports
You can import all exports from a module into a single namespace using the * as
syntax.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
// app.ts
import * as math from './math';
console.log(math.add(2, 3)); // Output: 5
console.log(math.subtract(5, 3)); // Output: 2
Dynamic Imports
Dynamic imports allow you to load modules asynchronously. This is useful for code-splitting and lazy loading.
// app.ts
async function loadMathModule() {
const math = await import('./math');
console.log(math.add(2, 3)); // Output: 5
}
loadMathModule();
Next: TypeScript Configuration