Modules in TypeScript
Use ES modules for modern TypeScript. Prefer named exports; avoid default exports in libraries for better refactoring.
Import and export
// math.ts
export function add(a: number, b: number) { return a + b }
export const PI = Math.PI;
// app.ts
import { add, PI } from "./math.js"; // with bundlers, extension often optional
console.log(add(1, 2), PI);
Default exports (use sparingly)
export default function main() {}
import main from "./main.js";
Default exports can complicate named refactors; prefer named exports in libraries.
Re-exports and barrels
// index.ts
export * from "./math.js";
export { add as plus } from "./math.js";
Module resolution
- Use
module: ESNextandmoduleResolution: Bundler(orNodeNextfor Node) - Configure path aliases in
tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "@/utils/*": ["src/utils/*"] }
}
}
Then import { x } from "@/utils/x".
Ambient modules and globals
Declare types for untyped modules or globals in *.d.ts.
// env.d.ts
declare const VERSION: string;
CommonJS interop
Set esModuleInterop: true and use default import syntax for CJS in many cases. For precise interop, use import = require() with module: commonjs.
Summary
- Prefer named exports and ES module settings
- Use path aliases and barrel files thoughtfully; declare ambient types where needed