How to use the module and commonjs patterns in JavaScript
· Category: JavaScript
Short answer
ES Modules use import/export and are statically analyzable, while CommonJS uses require/module.exports and evaluates dynamically at runtime.
Key differences
| Aspect | ESM | CommonJS |
|---|---|---|
| Syntax | import/export | require/module.exports |
| Loading | Static | Dynamic |
| Top-level await | Yes | No |
| Tree shaking | Yes | Harder |
| Browser native | Yes | No |
When to use each
- Use ESM for new projects, frontend code, and tree-shakeable libraries.
- Use CommonJS when targeting older Node.js versions or existing CJS ecosystems.
Example
// ESM
import { helper } from "./helper.js";
export const main = () => helper();
// CommonJS
const { helper } = require("./helper");
module.exports.main = () => helper();
Common issues
- Importing ESM from CommonJS requires dynamic
import()or transpilation. - File extensions are mandatory in ESM but optional in CommonJS.