CommonJS vs ESM

CommonJS in Node.js

Example

Node.js originally used CommonJS: require() and module.exports. It is still common in existing projects:

const path = require("path");
const { EventEmitter } = require("events");
console.log(path.join("src", "views", "index.html"));
const emitter = new EventEmitter();
emitter.on("greet", (name) => console.log("Hello", name));
emitter.emit("greet", "Asha");

Output

src\views\index.html
Hello Asha

Differences

CommonJSES Modules
Syntaxrequire / module.exportsimport / export
Loadingsynchronous, at runtimestatic, analysed before running
Tree shakinghardyes (bundlers drop unused exports)
Top-level awaitnoyes
In Nodedefault for .js files.mjs or "type": "module" in package.json