SyntaxStudy
Sign Up
TypeScript ES Modules: Import, Export, and Re-export
TypeScript Beginner 1 min read

ES Modules: Import, Export, and Re-export

TypeScript uses the ECMAScript module system by default. A module is any file containing at least one top-level import or export statement. Modules have their own scope — variables declared in a module are not visible outside unless explicitly exported. TypeScript adds type-only imports and exports which are erased at compile time and do not add any runtime cost. Exports can be named (using the export keyword before a declaration) or default (using export default). Named exports allow a module to export multiple values, each imported by its exact name. Default exports provide a single primary value per module, imported under any name the consumer chooses. You can also re-export values from other modules using export ... from syntax, which is useful for creating index files that aggregate a public API. Type-only imports (import type) are a TypeScript feature that guarantees the imported name is erased at runtime. This is important for avoiding circular dependencies caused by type-only relationships and for ensuring that module side effects are not unintentionally triggered. TypeScript 4.5 extended this to allow type-only specifiers within a regular import statement.
Example
// math.ts — named exports
export function add(a: number, b: number): number { return a + b; }
export function subtract(a: number, b: number): number { return a - b; }
export const PI = 3.14159265358979;

// types.ts — type-only exports
export type { User, Product };
interface User    { id: number; name: string }
interface Product { id: number; price: number }

// logger.ts — default export
export default class Logger {
    constructor(private prefix: string) {}
    log(msg: string): void { console.log(`[${this.prefix}] ${msg}`); }
}

// index.ts — aggregating re-exports
export { add, subtract, PI } from "./math";
export type { User, Product }  from "./types";
export { default as Logger }   from "./logger";

// app.ts — consuming the module
import { add, PI }     from "./math";
import type { User }   from "./types";  // type-only, erased at runtime
import Logger          from "./logger";

const logger = new Logger("App");
logger.log(`PI is approximately ${PI}`);
logger.log(`1 + 2 = ${add(1, 2)}`);

const user: User = { id: 1, name: "Alice" };
logger.log(`User: ${user.name}`);

// Inline type specifier (TS 4.5+)
import { type Product, add as addNumbers } from "./index";