ES Modules
export / import
Learn how modern JavaScript splits code into reusable modules using export and import statements.
What Is a Module?
A module is a single JavaScript file that keeps its variables and functions private by default. Nothing leaks into the global scope unless you explicitly export it.
Why Modules Matter
The Big Picture
Named Exports
A named export lets you expose any number of variables, functions, or classes by name. The importing file must use the exact same name (inside curly braces).
Default Exports
A default export designates a single main value from a module. The importer can name it anything they like: no curly braces required.
Named vs Default
| Named Export | Default Export | |
|---|---|---|
| Syntax (export) | export const x = ... | export default ... |
| Syntax (import) | import { x } from ... | import x from ... |
| Per module | Unlimited | Exactly one |
| Renaming | Needs as keyword | Free: any name works |
| Best for | Utility libraries | Single-purpose modules |
Renaming with as
If two modules export a value with the same name, you can rename on import using the as keyword to avoid collisions.
Re-exporting from a Barrel
A barrel file (often called index.js) collects exports from multiple modules into one convenient entry point.
How to Apply It
Example 1: Named Exports
Example 2: Default + Named
Example 3: Namespace Import
Use import * as to pull every named export into a single namespace object. This is handy when a module exports many related items.
Common Mistakes
Cheat Sheet
| Pattern | Export Syntax | Import Syntax |
|---|---|---|
| Named (inline) | export const x = ... | import { x } from ... |
| Named (list) | export { a, b } | import { a, b } from ... |
| Default | export default fn | import fn from ... |
| Rename | export { a as b } | import { a as b } from ... |
| Namespace | - | import * as M from ... |
| Re-export | export { x } from ... | - |
Question 1 of 5
Which syntax correctly imports a named export called sum from a module?
Question 2 of 5
How many default exports can a single JavaScript module have?
Question 3 of 5
Given export default function greet() {} in greet.js, which import is valid?
Question 4 of 5
What does import * as Utils from './utils.js'; do?
Question 5 of 5
You want to import a named export render from two different modules without a naming collision. Which approach works?