Runtime and core tooling · Lesson 2 of 18
CommonJS and ES modules
Split programs behind clear contracts and understand require/export and import/export.
A module is a file with private scope and a public contract. CommonJS uses require() and module.exports; ESM uses import and export, enabled through .mjs or "type": "module". A project should be explicit about its choice.
math.js hides details
exports public contract
app.js imports
module cache
const path = require("node:path")
const calculator = {
add(a, b) { return a + b },
label(file) { return path.basename(file) }
}
module.exports = calculator
console.log(calculator.add(4, 7), calculator.label("/tmp/app.js"))Node caches a module after its first require, so top-level code usually runs once. Export a small API rather than all internals, and avoid circular dependencies because they can expose partially initialized exports.
// ESM version (shown only; runnable lessons use CommonJS)
// math.mjs
export const add = (a, b) => a + b
// app.mjs
import { add } from "./math.mjs"
console.log(add(4, 7))Quick question
In CommonJS, how do you export one function directly?
Exercise
Complete an exported object with double, then print double(6).
Expected output: 12
const tools = {
}
module.exports = tools
console.log(tools.double(6))Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.