Lesson 5 of 30
CommonJS Modules
17% complete
Chapters
Chapter 5
CommonJS Modules
Learn the CommonJS module system using require and module.exports.
Theory
CommonJS is a module system traditionally used by Node.js.
CommonJS commonly uses:
require()
module.exports
require() is used to import a module.
module.exports is used to expose values from a module.
CommonJS modules are still widely found in existing Node.js applications.
Example
Node.js Example
// calculator.js
const add = (a, b) => a + b;
module.exports = add;
// app.js
const add = require("./calculator");
console.log(add(5, 7));Output
The exported function is imported using require() and returns 12.
Practice
Create a CommonJS module that exports a multiplication function.
Interview Questions
1.
What is CommonJS?
2.
What does require() do?
3.
What is module.exports?
Quick Quiz
Which option best matches this chapter?
A.require() and module.exports
B.importCSS and exportHTML
C.SELECT and INSERT
D.fetch and render
Answer: require() and module.exports