Careeroza
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
| CommonJS | ES Modules | |
|---|---|---|
| Syntax | require / module.exports | import / export |
| Loading | synchronous, at runtime | static, analysed before running |
| Tree shaking | hard | yes (bundlers drop unused exports) |
| Top-level await | no | yes |
| In Node | default for .js files | .mjs or "type": "module" in package.json |