Node.js Module System
Table of contents
No headings in the article.
Node.js has two module systems:
CommonJS Modules:
ECMAScript Modules (ESM):
CommonJS Modules:
This is the traditional module system in Node.js.
Files with
.cjs
extension are treated as CommonJS modules.Files with
.js
extension are treated as CommonJS modules unless the nearestpackage.json
file has"type": "module"
.You use
require()
to import modules andmodule.exports
to 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)); // 5
ECMAScript Modules (ESM):
This is the modern module system, aligned with the browser's module system.
Files with
.mjs
extension are treated as ES modules.Files with
.js
extension are treated as ES modules if the nearestpackage.json
file has"type": "module"
.You use
import
to import modules andexport
to export functionality.
// math.mjs export function add(a, b) { return a + b; } // app.mjs import { add } from './math.mjs'; console.log(add(2, 3)); // 5
Key Differences:
Syntax: ESM uses
import
andexport
, while CommonJS usesrequire
andmodule.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 !