TypeScript Modules
Modules let you split your code across multiple files, exporting the pieces you want to share and importing them where needed. This keeps large codebases organized and manageable.
TypeScript uses the same `export` and `import` syntax as modern JavaScript (ES modules), so anything you already know about ES modules applies directly to TypeScript files.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// app.ts
import { add } from "./math";Exporting
You can export individual items with `export` in front of a declaration, such as `export function add() {}`, or export a single default item per file with `export default`.
Importing
You bring exported items into another file with `import { add } from "./math";` for named exports, or `import add from "./math";` for a default export.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}(no direct output โ a module file)The add function is exported so other files can import and use it.
// app.ts
import { add } from "./math";
console.log(add(2, 3));5app.ts imports the named export add from math.ts and calls it.
Key points
- Modules split code across multiple files.
- `export` shares a value, function, class, or type from a file.
- `import` brings exported items into another file.
- TypeScript uses standard ES module import/export syntax.
