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:
module.exports object, which is used to export stuffrequire function, which is used to import stuff// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = {
add,
subtract,
};
// main.js
const { add, subtract } = require("./math.js");
console.log(add(1, 2)); // 3
console.log(subtract(1, 2)); // -1