Modules & Organization
Lesson Overview
Learn how to structure and organize your TypeScript code using ES Modules and Namespaces.
Modules & Organization
As your TypeScript projects grow, it becomes essential to split your code into multiple files. TypeScript supports the modern ES Module system, which is the standard for both web and Node.js development.
Exporting & Importing
You can export variables, functions, interfaces, or classes from a file using the export keyword.
// math-utils.ts
export const PI = 3.14;
export function add(a: number, b: number): number {
return a + b;
}
export default class Calculator {
// ...
}
To use these in another file, use the import keyword:
// app.ts
import Calculator, { add, PI } from "./math-utils";
console.log(add(10, PI));
Import Types Only
A great feature of TypeScript is the ability to import only the types. This ensures that no JavaScript code is generated for that import, which can improve performance and avoid circular dependency issues.
import type { User } from "./models";
Namespaces
Before the ES Module system became the standard, TypeScript used Namespaces to organize code. While Modules are now preferred, you might still encounter Namespaces in older projects or when writing definition files (.d.ts).
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
export const numberRegexp = /^[0-9]+$/;
}
Which should you use?
Always use ES Modules (import/export) for modern projects. Namespaces are primarily for legacy code or specific structural needs within a single file. Modules provide better isolation, better tooling support, and are the standard in the JavaScript ecosystem.
Project Structure Best Practices
- One feature per file: Keep files small and focused.
- Use Folder Indexing: Create an
index.tsin folders to “re-export” everything for cleaner imports. - Barrel Exports:
Then you can import as:// components/index.ts export * from "./Button"; export * from "./Input";import { Button, Input } from "./components";