Modules allows us to organize code into reusable modules making it easier to manage, test and scale the applications.
1️⃣ CommonJS Modules
CommonJS is the traditional module system in Node.js, using require()
to import modules and module.exports
to export them.
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// main.js
const math = require('./math');
console.log(math.add(2, 3)); // 5
2️⃣ ES Modules (ESM)
ES Modules are a standardized module system that use import
and export
syntax. They are now fully supported in Node.js with certain configuration.
// math.mjs
export function add(a, b) {
return a + b;
}
// main.mjs
import { add } from './math.mjs';
console.log(add(2, 3)); // 5