ES modules

Export

Export shares functions, classes, and constants from one file. Other files can only use what the source file chooses to export.

export function add(a: number, b: number): number { return a + b; } export const version: string = "1.0";

Import

Import brings exported names into the current file. Named imports list each name in braces and must match the export spelling.

import { add, version } from "./math.js"; console.log(add(2, 3)); console.log(version);

Default exports

A module can have one default export for its main value. Default imports skip the braces and may choose any local name.

export default function greet(name: string): string { return "Hello " + name; } import greet from "./greet.js"; console.log(greet("Ada"));

Extensions in imports

With Node style resolution, relative imports keep the compiled .js extension even though the source file on disk is a .ts file. The compiler maps the .js path back to the matching source.

Write math.js in the import while editing math.ts, and the build will resolve it correctly.

import { add } from "./math.js"; const total = add(2, 3); console.log(total);

Next: Decorators

Article author: Arthur Isaev

Banner image