Modules
ES Modules (import /export) are the standard way to split JavaScript code into reusable, encapsulated pieces. They enable tree-shaking, static analysis, and clean dependency graphs.
How do import and export work in JavaScript?
ES modules split code into files that share values explicitly. Use export to make a function or variable available and import to use it in another file. Each file can also have one export default. In the browser, load the entry file with <script type="module" src="main.js">; modules are deferred and strict by default.
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default function circle() { … }
// main.js
import circle, { area, PI as pi } from "./math.js";
const { heavy } = await import("./heavy.js"); // dynamic importNamed Exports
Default Export
Dynamic Imports
import() is a function that returns a Promise and loads the module lazily — only when called. Perfect for code splitting, conditional loading, and route-based chunking.
Key Module Characteristics
Common Pitfalls
Interactive Examples
Code Editor
<pre>// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
// main.js
import {
area,
PI,
} from "./math.js";</pre>
<p id="out"></p>Preview
ES modules — step by step
Named vs default exports
Named exports: export const fn = () => {} — multiple per file, imported with braces: import { fn } from './module'. Default export: export default class Foo {} — one per file, imported without braces and with any name: import Foo from './module'. Prefer named exports for most cases — they are easier to refactor and work better with tree shaking.
🎯 Quick Check
Why do bundlers tree-shake ES modules more effectively than CommonJS?
JavaScript Modules: summary
Key points
- Named imports must match the exported names (rename with
as); a default import can use any name. - In the browser, module paths need the extension (
./math.js) unless a bundler resolves them. - Dynamic
import()loads code on demand, which is the basis of code splitting. - Modules run once, however many files import them.
Frequently asked questions
›Should I use default or named exports?
Many teams prefer named exports: they keep names consistent and work better with auto-imports and refactoring. Default exports suit modules with one main thing, like a React component.
›Why do I get "Cannot use import statement outside a module"?
The file is loaded as a classic script. Add type="module" to the script tag, or set "type": "module" in package.json for Node.js.