CommonJS vs ES Modules
Node.js supports two module systems: CommonJS (the original `require`/`module.exports` system) and ES Modules (the modern `import`/`export` standard shared with browsers).
By default Node uses CommonJS, but you can opt into ES Modules by using the `.mjs` extension or adding `"type": "module"` to package.json.
CommonJS
CommonJS is synchronous and uses `require()` and `module.exports`. It has been Node's default since the beginning.
ES Modules
ES Modules use `import` and `export` syntax, support top-level await, and are the standard used in modern JavaScript everywhere, including browsers.
// CommonJS
const fs = require('fs');
module.exports = { hello: () => 'hi' };Classic Node.js syntax using require and module.exports.
// ESM (file.mjs or type: module)
import fs from 'fs';
export function hello() { return 'hi'; }Modern syntax matching browser JavaScript modules.
Key points
- CommonJS uses require()/module.exports.
- ES Modules use import/export.
- Set "type": "module" in package.json to use ESM by default.
- You cannot mix the two syntaxes in the same file.
