We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

CommonJS

So we've started with the less preferred way of doing modules in JavaScript: CommonJS. CommonJS is a module system that was created for Node.js before the new ES6 module syntax was introduced. It's still used in Node.js today, but ever since Node added support for ES6 modules, it's become less common. (heh, get it?)

CommonJS is Node.js specific, you can't use it in the browser without some kind of bundler, which we'll talk about in a bit. The defining features of CommonJS are:

  • The module.exports object, which is used to export stuff
  • The require function, which is used to import stuff

Exporting

// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports = {
  add,
  subtract,
};

Importing

// main.js
const { add, subtract } = require("./math.js");

console.log(add(1, 2)); // 3
console.log(subtract(1, 2)); // -1