← Back to TypeScript Course | Chapter 9: Modules and Namespaces | Lesson 1 of 7

ES Modules in TypeScript

ES modules let you split TypeScript programs into separate files and share code between them. Each file can export values and import values from other modules.

Creating a Module

A TypeScript file becomes an ES module the moment it uses import or export; exported declarations become available to other files, while everything else stays private to that file.

Example: Creating a Module

typescript
// math.ts
export function square(x: number): number {
  return x * x;
}
const privateHelper = 42; // not exported, stays private

console.log(square(5));

Named Exports

Named exports allow a module to expose multiple declarations at once by writing export in front of each one, and importers choose exactly which named exports they want to bring in.

Example: Named Exports

typescript
// shapes.ts
export const PI = 3.14159;
export function circleArea(radius: number): number {
  return PI * radius * radius;
}

console.log(circleArea(2));

Importing Modules

The import statement lets one module use declarations exported by another module; the imported names must match the exported names unless an alias is used to rename them. Import paths can point to other project files, packages, or built-in Node modules.

Example: Importing Modules

typescript
// shapes.ts
export function circleArea(radius: number): number {
  return 3.14159 * radius * radius;
}

// main.ts
// import { circleArea } from "./shapes";
console.log(circleArea(3));

Import Aliases

An imported declaration can be renamed with the as keyword, which is useful when two modules export something under the same name and both need to be imported into the same file.

Example: Import Aliases

typescript
// shapes.ts
export function area(radius: number): number {
  return 3.14159 * radius * radius;
}

// main.ts
// import { area as circleArea } from "./shapes";
const circleArea = area;
console.log(circleArea(4));

Module Organization

Modules help organize large applications by keeping related declarations together in their own file; a project's overall structure often mirrors its module boundaries, one concern per file.

Example: Module Organization

typescript
// utils/math.ts
export function double(x: number): number {
  return x * 2;
}

// utils/string.ts
export function shout(s: string): string {
  return s.toUpperCase() + "!";
}

console.log(double(5), shout("hi"));
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.