Junior — Middle
What are the main approaches and mechanisms for ensuring modularity used in Node.js?
sobes.tech AI
Answer from AI
In Node.js, modularity is provided by several main mechanisms:
-
CommonJS modules — the standard way of organizing code, where each file is a module with
module.exportsandrequire()for importing. -
ES6 modules (ESM) — a modern standard using
exportandimport. -
npm packages — allow sharing and reusing code, managing dependencies.
-
Code organization patterns — for example, dividing into controllers, services, models.
-
Use of bundlers (Webpack, Rollup) — for combining modules into a single file.
Example of a CommonJS module:
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// app.js
const math = require('./math');
console.log(math.add(2, 3));
Example of an ES6 module:
// math.mjs
export function add(a, b) {
return a + b;
}
// app.mjs
import { add } from './math.mjs';
console.log(add(2, 3));