Learn the concept
Module System
TypeScript supports ES6 modules with import/export syntax. Use 'import type' for type-only imports (erased at compile time). Declaration files (.d.ts) provide types for JavaScript libraries. Module resolution follows Node.js or bundler strategies.
Module Syntax:
import/exportexport { name }export defaultimport * asType-Only Imports:
import type { Type }: Types only, erased at runtimeimport { type Type }: Inline type modifierDeclaration Files (.d.ts):
@types/* packages from DefinitelyTypedModule Resolution:
Modern Settings:
verbatimModuleSyntax (TS 5.0+): Enforces explicit import type, replacing deprecated isolatedModules/importsNotUsedAsValuesimport defer * as mod from 'module' (TS 5.9): Deferred module evaluation.mts/.cts extensions for explicit ESM/CJS module files// === Exporting ===
// Named exports
export const PI = 3.14159;
export function add(a: number, b: number): number {
return a + b;
}
export interface User {
id: number;
name: string;
}
// Default export
export default class Calculator {
add(a: number, b: number) { return a + b; }
}
// Re-exports
export { User as UserType } from './types';
export * from './utils';
export * as MathUtils from './math';
// === Importing ===
// Named imports
import { PI, add, User } from './math';
// Default import
import Calculator from './calculator';
// Namespace import
import * as Math from './math';
Math.add(1, 2);
// Combined
import Calculator, { add, PI } from './calculator';Configuring dual CJS/ESM exports with proper type declarations using package.json exports field
Extending third-party library types (Express Request, Next.js PageProps) via module augmentation
Organizing large codebases with index.ts barrel files using type-only re-exports
Create a library that publishes both ESM and CJS with correct .d.ts, .d.mts, and .d.cts declarations
Build a plugin system that extends a core library's types via declaration merging