ES Modules in TypeScript
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
// 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
// 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
// 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
// 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
// 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: