Concept Explanation
Real apps aren't one giant file — they're dozens of small files that share code. ES Modules (ESM) are JavaScript's official system for this: each file exports what it wants to share, and other files import exactly what they need.
Picture a kitchen: each file is a specialist station that hands out one dish (export), and the head chef (import) pulls in only the dishes required for tonight's menu. No global mess, clear dependencies.
Syntax or Core Structure
Named vs. default exports
// math.js
export const PI = 3.14159; // named export
export function square(n) { return n * n; }
export default function add(a, b) { return a + b; } // one default per file
// app.js
import add, { PI, square } from './math.js';
import * as math from './math.js'; // grab everything as one object
add(2, 3); // 5 (the default, importable under any name)
square(PI); // named, must match the exported name
In the browser, mark the script as a module: <script type="module" src="app.js"></script>.
Real World Example
Every import React from 'react' line you'll ever write is ESM in action. Bundlers like Vite read your import graph to learn exactly which files your app touches, then ship only those — and drop the code you never import (a trick called "tree shaking").
Common Mistakes
- Default vs. named mix-up:
import { add }fails ifaddwas a default export. Default imports skip the curly braces. - Forgetting
type="module": a plain<script>tag doesn't understandimportand throws "Cannot use import statement outside a module." - Missing the extension: in native browser ESM the path usually needs the
.jsextension. Bundlers are forgiving; the browser is strict.
Best Practices
- One default, many named: reserve the default export for a file's "main thing"; use named exports for helpers.
- Keep modules focused: a module should export one clear concept, not a grab-bag of unrelated functions.
- Prefer static imports: they let bundlers tree-shake. Use dynamic
import()only for code you want to load on demand.
Practice Exercises
- The Toolbox: Create a
utils.jsthat exports two named helpers, then import and use both from another file. - The Default: Give a
User.jsfile a default-exported class and import it under a name of your choosing. - The Namespace: Use
import * as utilsto call three helpers through a singleutils.prefix.