Skip to content
TypeScript Essentials

TypeScript Modules

Beginner Lesson 7 of 9

Modules help organize code into separate files with explicit dependencies.

// Named exports
export const PI = 3.14159;
export function add(a: number, b: number): number {
return a + b;
}
export class Calculator {
// ...
}
// Export at end of file
const subtract = (a: number, b: number) => a - b;
export { subtract };
// Export with rename
export { subtract as minus };
// Default export
export default class User {
constructor(public name: string) {}
}
// Or
class User {
constructor(public name: string) {}
}
export default User;
// Import named exports
import { PI, add, Calculator } from "./math";
// Import with alias
import { add as sum } from "./math";
// Import all as namespace
import * as math from "./math";
math.add(1, 2);
// Import default
import User from "./user";
// Import both
import User, { Role } from "./user";
// Re-export from another module
export { User } from "./user";
export { PI, add } from "./math";
// Re-export all
export * from "./utils";
// Re-export with rename
export { User as Person } from "./user";
// Import types only (removed at runtime)
import type { User } from "./user";
// Mixed imports
import { createUser, type User } from "./user";
// tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"baseUrl": "./src",
"paths": {
"@/*": ["./*"],
"@utils/*": ["./utils/*"]
}
}
}
// Usage
import { helper } from "@utils/helper";

Continue to Decorators →