Modules
A large application does not fit comfortably in one file. Modules let us split the code into separate files, and each file holds one group of related functionality. That makes the code easier to maintain, it lets us reuse a file in more than one place, and it keeps names in one file from clashing with names in another.
// math.js
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
// app.js
import { add, multiply } from "./math.js";
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
ES6 (ECMAScript 2015) introduced a standardized module system for JavaScript. Before ES6, developers relied on patterns like IIFEs and module systems like CommonJS (used in Node.js). Today, ES6 modules are the standard for both browser and server-side JavaScript.
Learning Outcomes
- Explain the purpose of ES6 modules and configure them in browser and Node.js environments
- Export and import functionality between modules, including named exports, default exports, and aliases
- Distinguish module syntax from type-related syntax
- Explain how JavaScript handled code encapsulation before ES6, including IIFEs and CommonJS
- Apply module concepts to organize and reason about multi-file JavaScript applications