iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Modules

A TypeScript module is a file that exports something. Imports/exports use the ES module syntax — TypeScript adds type-only imports for performance.

Exports

TS — math.ts
export const PI = 3.14159;

export function area(r: number): number {
    return PI * r * r;
}

export interface Point {
    x: number;
    y: number;
}

export default class Vec2 {
    constructor(public x: number, public y: number) {}
}

Imports

TS — app.ts
import Vec2, { PI, area, type Point } from './math';
import * as math from './math';        // namespace import
import { default as Vec2Alias } from './math';   // rename default

type-only imports/exports

Pure type imports are erased at compile — using import type makes bundlers smarter:

TS
import type { User } from './types';
import { type Config, loadConfig } from './config';

export type { Result } from './result';

Re-exports

TS — index.ts (barrel)
export { Button } from './Button';
export { Card }   from './Card';
export * from './form';
export { default as Logo } from './Logo';

File extensions

With "module": "NodeNext", imports must include the output file extension:

TS
import { area } from './math.js';      // .js even though source is .ts

This is what plain Node expects. Bundlers usually let you drop the extension.

Dynamic imports

TS
const { renderChart } = await import('./chart');
renderChart();
Tip: Decide on one module style per project — "module": "NodeNext" for Node libraries, "module": "Bundler" for Vite/Webpack apps. Mixing causes weeks of mysterious resolution errors.

Example

Example
// math.ts
// export function add(a: number, b: number) { return a + b; }
// export const PI = 3.14159;

// app.ts
// import { add, PI } from './math';
// import * as math from './math';
// import math from './math';   // default

console.log('See the project lessons for runnable demos.');
Try it Yourself »

Exercise

Import a type-only export with this keyword.

import { User } from './types';

Test yourself

Q1. For type-only imports use…
Q2. Default export uses…
Q3. Module resolution preferred for modern Node is…

Discussion

Loading…