Node.js ยท Chapter 5 of 43

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.

Example 1 (javascript)
// CommonJS
const fs = require('fs');
module.exports = { hello: () => 'hi' };

Classic Node.js syntax using require and module.exports.

Example 2 (javascript)
// 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.
๐Ÿ’ก Note: Use `.cjs` to force CommonJS in an ESM project, or `.mjs` to force ESM in a CommonJS project.

๐Ÿ“ Quick Quiz

1. Which keyword system does CommonJS use?

2. How do you enable ES Modules by default in package.json?

3. Which file extension forces ESM regardless of package.json?