Modern JS (ES6+)
Modules (import / export)
Splitting code into reusable files with ES modules.
ES modules let you split code across files and share it with export and import, replacing the old global-script and CommonJS (require) approaches in the browser.
Modules are like labelled shipping containers: each file exports specific goods, and other files import exactly what they need.
Key concepts
1
A file can have any number of named exports and at most one default export. Imports are live, read-only bindings to the exported values, and modules run in strict mode and are evaluated only once, then cached.
named exportsdefault exportlive, read-only bindings
2
Static import statements enable tree-shaking (dead-code elimination); dynamic import() returns a promise for code-splitting and lazy loading.
tree-shakingimportimport()
javascript
// math.js
export const add = (a, b) => a + b; // named
export default function subtract(a, b) { return a - b; } // default
// app.js
import subtract, { add } from './math.js';
add(2, 3); // 5
subtract(5, 2); // 3
// lazy load
const mod = await import('./math.js');