CommonJS vs ES Modules
Node.js historically used CommonJS (require/module.exports). ES Modules (import/export) are now the standard in both browsers and modern Node.js.
Node.js historically used CommonJS (require/module.exports). ES Modules (import/export) are now the standard in both browsers and modern Node.js.
// CommonJS (Node.js legacy)
const fs = require("fs");
const { add } = require("./math");
module.exports = { greet };
// ES Modules (modern standard)
import fs from "fs";
import { add } from "./math.js";
export { greet };
// Key differences:
// ESM: static analysis, tree-shakable, async
// CJS: dynamic require(), synchronous, widely used in npm
Use .mjs extension or add "type": "module" to package.json to enable ES modules in Node.js.
More in JavaScript