Beginner Fundamentals

Modules in Node.js

Modules let you split code into separate files and reuse it. Node.js supports two systems: CommonJS (the classic one) and ES modules (the modern standard).

CommonJS

CommonJS uses require to import and module.exports to export.

// math.js
function add(a, b) {
  return a + b;
}
module.exports = { add };
// app.js
const { add } = require("./math");
console.log(add(2, 3)); // 5

ES modules

ES modules use import and export. To enable them, set "type": "module" in package.json or use the .mjs extension.

// math.mjs
export function add(a, b) {
  return a + b;
}
// app.mjs
import { add } from "./math.mjs";
console.log(add(2, 3)); // 5

Which one to use

  • CommonJS is the default in older projects.
  • ES modules are the modern, browser compatible standard.

Summary

Both systems let you organize code. Pick one style per project and stay consistent.