0Pricing
JavaScript Academy · Lesson

CommonJS basics — require/module.exports and exports

Learn CommonJS: require(), module.exports, exports shortcut, and a small interop taste with ESM.

CJS: big picture

Goal: Read and write small CommonJS modules.

  • require() loads modules
  • module.exports is the export object
  • exports is a shortcut to the same object
  • Quick ESM interop taste
CommonJS basics — require/module.exports and exports — illustration 1

require() — idea

require(path) returns the module's exported object in CommonJS.

// CommonJS import uses require()
const cjsExample = [
  "const math = require(\\"./math.js\\");",
  "console.log(math.sum(2, 3));"
];

console.log("require() example:");
for (const line of cjsExample) console.log(line);

// Emulate a loaded module object
const loaded = { sum: function (a, b) { return a + b; } };
console.log("emulated require sum:", loaded.sum(2, 3));
CommonJS basics — require/module.exports and exports — illustration 2

All lessons in this course

  1. ESM basics — import/export, default vs named
  2. CommonJS basics — require/module.exports and exports
  3. Module resolution in Node and browser bundlers
← Back to JavaScript Academy