Node.js Module System
Node.js has two module systems:
CommonJS Modules:
ECMAScript Modules (ESM):
CommonJS Modules:
This is the traditional module system in Node.js.
Files with
.cjsextension are treated as CommonJS modules.Files with
.jsextension are treated as CommonJS modules unless the nearestpackage.jsonfile has"type": "module".You use
require()to import modules andmodule.exportsto export functionality.example -
// math.js function add(a, b) { return a + b; } module.exports = { add }; // app.js const math = require('./math'); console.log(math.add(2, 3)); // 5ECMAScript Modules (ESM):
This is the modern module system, aligned with the browser's module system.
Files with
.mjsextension are treated as ES modules.Files with
.jsextension are treated as ES modules if the nearestpackage.jsonfile has"type": "module".You use
importto import modules andexportto export functionality.
// math.mjs export function add(a, b) { return a + b; } // app.mjs import { add } from './math.mjs'; console.log(add(2, 3)); // 5Key Differences:
Syntax: ESM uses
importandexport, while CommonJS usesrequireandmodule.exports.Asynchronous: ESM is asynchronous by nature, allowing for better performance.
Compatibility: ESM is the future standard, while CommonJS is still widely used.
Choosing the Right Module System:
For new projects, ESM is recommended.
For existing projects using CommonJS, you can gradually migrate to ESM.
If you need to support older Node.js versions, CommonJS is your only option.
Thank you !