CommonJS
CommonJS is the original module system created specifically for Node.js, long before the JavaScript language had official module support built-in.
Because it was designed for servers, CommonJS relies on reading files synchronously from a local hard drive. It cannot be run directly in a web browser without the help of a build tool (a bundler).
While CommonJS is now considered legacy syntax, you will still encounter it constantly in older Node.js projects and configuration files.
CommonJS Syntax
The defining features of CommonJS are the module.exports object and the require() function.
Exporting (math.js)
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
// Expose these functions to the rest of the application
module.exports = {
add,
subtract,
};
Importing (main.js)
// Pull the exported functions out of the math file
const { add, subtract } = require("./math.js");
console.log(add(1, 2)); // 3