When an app grows beyond a small script, split its JavaScript into files with explicit responsibilities. An ECMAScript module (ESM) is a browser-native JavaScript module with its own scope: it shares functionality through `export` and consumes other modules through `import`. Load an entry file with `<script type="module" src="/app.js"></script>` rather than placing all startup logic in one file. section 5.5 section 14.7.2
The browser fetches modules by URL and follows their imports to build a dependency graph. It then links imports to exports and evaluates each module once, in dependency order. Imports are live bindings, not copied values: an importer can observe an exported variable after it changes. Repeated imports share the same module instance and state. section 5.5 section 5.5.10
Export a small API
In `math.js`: `export function add(a, b) { return a + b; }` and `export default function square(n) { return n * n; }`. In `app.js`: `import square, { add } from './math.js';`. Named exports use braces; a module may also have one default export, imported without braces. section 5.5.1
Keep module boundaries predictable:
- Minimize top-level side effects. Export an explicit `init()` function when setup needs a clear starting point; otherwise, any import can trigger that setup. section 5.5.10
- Take care with circular imports: linking accommodates cycles, but reading a binding too early can still produce an undefined value. section 5.5
- Check target-browser support before shipping newer syntax. A legacy requirement may call for a separate `nomodule` fallback; bundling or transpiling is an option, not a prerequisite for browser-ready modules. section 5.2 section 5.5.10
Modules also support dynamic imports, import maps, top-level await, and preload strategies. These are options to consider as loading requirements grow, rather than reasons to add a build step by default. section 5.10 section 14.1.10
A standalone module can distribute a custom element that registers when imported, or expose named exports for a small library. Local files, package-manager entries, and CDN URLs are possible delivery paths; a published CDN path becomes part of the consumer-facing contract. section 9.9.1 section 9.9.3 section 14.1.10

