Modules
How JavaScript code is split across files with import/export, and the difference between the ES Module and CommonJS systems.
Why modules
Modules let you split code across files, expose only what's needed (export), and pull in what you need from elsewhere (import) instead of relying on global variables shared across every script on the page.
Named exports
Export multiple named values from a file:
Default exports
Each file can additionally have one default export typically the "main thing" that file provides:
A file can mix a default export with named exports:
Re-exporting
Useful for creating a single "barrel" file that re-exports things from several modules:
ESM vs CommonJS
There are two competing module systems in the JS ecosystem:
ES Modules (ESM) the standard, import/export syntax shown above. Used natively in browsers and modern Node.js. Statically analyzable (imports are resolved before code runs), which enables tree-shaking (bundlers can drop unused exports).
CommonJS (CJS) Node's original module system, still common in older packages and tooling:
Key differences:
- ESM imports are resolved statically at build time; CommonJS
require()runs at runtime and can be called conditionally (e.g. inside anif). - ESM is asynchronous-friendly (top-level
awaitis allowed); CommonJSrequire()is always synchronous. - Node.js determines which system a file uses based on the
typefield inpackage.json("type": "module"for ESM) or the file extension (.mjsvs.cjs).