

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Modules
incomplete
2: CommonJS
incomplete
3: Strict Mode
incomplete
4: ES6 Modules
incomplete
5: Node.js Modules
incomplete
6: Browser Modules
incomplete
7: Default Exports
incomplete
8: Bundlers
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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