Level 10
Modules
Organize code across files with ES modules: named and default exports, imports, type-only imports, barrel files, and how module resolution and path aliases work in TypeScript.
20 min read + quiz
Why Modules Exist
A module is simply a file with its own scope. Anything declared in a module, including variables, functions, classes, and types, is private to that file unless explicitly exported. This is the opposite of classic script files, where every top-level declaration lands in the global scope and any file can trample another's variables.
In TypeScript, a file becomes a module the moment it contains at least one import or export statement. Files without either are treated as global scripts, which is almost never what you want in a modern project; it is why a brand-new .ts file sometimes shows odd errors like 'Cannot redeclare block-scoped variable' until you add an export.
Modules are the unit of organization, encapsulation, and reuse. Well-drawn module boundaries, where each file exports a small, deliberate API and keeps its internals private, do as much for a codebase's health as any type annotation.
// math.ts - a module: everything is private unless exported
const SECRET_SEED = 42; // not exported: file-private
export const PI = 3.14159;
export function circleArea(radius: number): number {
return PI * radius * radius;
}
// main.ts
// import { circleArea, PI } from "./math";
// console.log(circleArea(2), PI);
// SECRET_SEED is invisible here - encapsulation by default.Exports define a module's public API; everything else stays private to the file.
Named Exports and Imports
Named exports are the workhorse: prefix any declaration with export, and consumers import it by its exact name inside curly braces. A module can have any number of named exports, and importers pick exactly what they need. Because names must match, typos fail at compile time, and editors can auto-import and rename across the whole project reliably.
You can rename on either side with 'as', import everything at once as a namespace object ('import * as math'), and re-export from another module ('export { helper } from "./utils"'). Renaming is handy when two modules export the same name.
Named exports also help bundlers: because the dependency graph is fully static, meaning imports cannot be constructed at runtime, tools can tree-shake, dropping exports nothing imports. Deep, precise imports keep your shipped JavaScript small.
// format.ts
export function currency(n: number): string {
return "$" + n.toFixed(2);
}
export function percent(n: number): string {
return (n * 100).toFixed(1) + "%";
}
// report.ts
// import { currency, percent as pct } from "./format";
// import * as format from "./format";
//
// console.log(currency(9.5)); // "$9.50"
// console.log(pct(0.25)); // "25.0%"
// console.log(format.currency(1)); // namespace-style accessNamed imports, renaming with 'as', and namespace imports of a whole module.
Default Exports and the Trade-offs
A module may additionally declare one default export: 'export default function App() {...}'. Importers write 'import App from "./App"' with no braces, and, notably, they may choose ANY local name; nothing forces the importer's name to match the module's.
That freedom is precisely the criticism: the same component can be imported as App, Application, and MyApp in three files, hurting searchability and enabling silent inconsistency. Named exports keep one canonical name everywhere and give better autocomplete and auto-import behavior. Many style guides, including several prominent ones, recommend avoiding default exports for these reasons.
You cannot always avoid them: some frameworks require default exports by convention, for example page and layout files in Next.js. The pragmatic policy is to use default exports where a framework demands them and named exports for everything else.
// button.ts
export default function Button(label: string): string {
return "[" + label + "]";
}
export const BUTTON_HEIGHT = 40; // default and named can coexist
// app.ts
// import Button from "./button"; // no braces, any name works
// import Btn from "./button"; // same import, different name!
// import { BUTTON_HEIGHT } from "./button";
//
// console.log(Button("Save"), BUTTON_HEIGHT);Default imports need no braces - and importers can pick any name, for better or worse.
Exporting and Importing Types
Interfaces and type aliases are exported and imported with exactly the same syntax as values, and one import statement can mix both. But types and values have different fates: types are erased at compile time, so importing a type creates no runtime dependency at all.
TypeScript lets you make that distinction explicit with type-only imports: 'import type { User } from "./types"' guarantees the import vanishes entirely from the compiled output. You can also mark individual specifiers within a mixed import: 'import { createUser, type User } from "./users"'.
This matters more than it first appears. Build tools that compile one file at a time cannot always tell whether an imported name is a type or a value, and a type-only import that is not marked can leave behind a broken runtime import statement. The verbatimModuleSyntax compiler option enforces marking, and many codebases, including this one, treat 'import type' as standard practice for all type imports.
// types.ts
export interface User {
id: number;
name: string;
}
export type Role = "admin" | "member";
// service.ts
// import type { User, Role } from "./types"; // erased entirely
//
// export function promote(user: User): Role {
// return user.id === 1 ? "admin" : "member";
// }import type guarantees zero runtime footprint and keeps single-file build tools happy.
Module Resolution, Barrels, and Path Aliases
When you write an import, TypeScript must resolve the specifier to a file. Relative specifiers ('./utils', '../lib/math') resolve from the importing file's location; bare specifiers ('react') resolve through node_modules. The moduleResolution setting in tsconfig controls the exact rules; modern projects typically use the 'bundler' mode, which matches how tools like Vite and Next.js behave.
A barrel is an index.ts that re-exports a folder's public API, letting consumers write one clean import ('from "./components"') instead of many deep ones. Barrels tidy up import statements but have real downsides at scale: they can drag the entire folder into every consumer's compile and bundle, slow builds, and create accidental circular imports. Use them for a package's deliberate public boundary, not reflexively in every folder.
Path aliases eliminate ../../../ chains: mapping '@typescript/*' to 'src/*' in tsconfig's paths option lets any file import from '@typescript/lib/types'. The alias in this very project is why lesson files import from '@typescript/lib/types'. Remember tsconfig paths only inform the type checker; your bundler or runtime must be configured to match, though most frameworks wire this up for you.
// tsconfig.json (excerpt)
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@typescript/*": ["./src/*"]
}
}
}
// Deep in src/features/admin/panel.ts - no ../../.. needed:
// import type { User } from "@typescript/lib/types";
// import { formatDate } from "@typescript/lib/format";A paths alias maps @typescript/ to src/, keeping imports stable no matter how deep the file lives.
Try it yourself
This lesson's example is preloaded in the playground — break it, fix it, extend it.
Open in playgroundCheck your understanding
Question 1 · Multiple choice
What makes a TypeScript file a module rather than a global script?
Question 2 · Multiple choice
What is the practical benefit of 'import type { User } from "./types"' over a plain import?
Question 3 · Find the error
Module math.ts contains the code shown. Why does the import in main.ts fail?
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// main.ts
import { sum } from "./math";
console.log(sum(2, 3));Question 4 · True or false
When importing a default export, the importing file must use the same name the exporting module used.
Question 5 · Predict the output
Given these two modules compiled and run together, what does main.ts print?
// counter.ts
let count = 0;
export function increment(): number {
count += 1;
return count;
}
// main.ts
import { increment } from "./counter";
console.log(increment());
console.log(increment());
console.log(increment());