ES Modules: import & export
Break your codebase into manageable files. Learn the syntax for named and default exports to share code across your application.
The Module System
Historically, all JavaScript was dumped into a single massive file or loaded via multiple <script> tags, causing global variables to collide and overwrite each other.
**ES Modules (ESM)** is the modern standard for organizing JavaScript. It allows you to break your code into separate files (modules) that have their own private scope. You explicitly declare what to share (export) and what to bring in (import).
Named vs Default
There are two ways to export data from a module:
1. **Named Exports:** Use when exporting multiple things. You must use the exact same name when importing, wrapped in curly braces: import { sum, multiply } from './math.js';
2. **Default Exports:** Use when a file exports exactly one primary thing (like a single React component). You can name it whatever you want when importing, without curly braces: import MathLibrary from './math.js';
Writing Modules
To create a named export, put the keyword in front of the declaration:
javascript
export const PI = 3.14;
export function add(a, b) { return a + b; }
To create a default export, use export default:
javascript
export default function calculateArea(r) { return PI * r * r; }
Visualizing the Wiring
Study the architecture diagram below. It illustrates the exact syntax required to wire an exported variable from one file into an imported variable in another.
The Module Bridge
console.log(sum(2, 2)); // 4
Named exports strictly require { curly braces }. Defaults do not.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- ES Modules (ESM) give every file its own private scope.
- Use **Named Exports** (
export const x) for multiple items, and import them with curly braces (import { x }). - Use **Default Exports** (
export default x) for a single main item, and import without curly braces. - Named imports must use the exact name, while Default imports can be named anything by the importer.
- Use the
askeyword to rename a Named import to prevent naming collisions.
Done with this concept?
Mark it complete to track your progress. No login needed.