Learn the concept
Modules
The Module pattern encapsulates code using closures to create private state. ES6 modules are the standard with static imports (analyzed at compile time), while CommonJS uses dynamic require() at runtime. ES6 supports tree-shaking and async loading.
Classic Module Pattern:
CommonJS (Node.js):
require() for imports, module.exports for exportsES6 Modules:
import/export syntax// Revealing Module Pattern
const Calculator = (function() {
// Private state
let result = 0;
// Private function
function validate(n) {
if (typeof n !== 'number') throw new Error('Not a number');
}
// Public API
return {
add(n) {
validate(n);
result += n;
return this;
},
subtract(n) {
validate(n);
result -= n;
return this;
},
getResult() {
return result;
},
reset() {
result = 0;
return this;
}
};
})();
Calculator.add(5).add(3).subtract(2).getResult(); // 6
// Calculator.result is undefined (private)Publishing libraries with both ESM and CJS builds using package.json conditional exports for maximum ecosystem compatibility
Using Module Federation or import maps to share modules across independently deployed micro-frontends at runtime
Using the IIFE Module pattern for isolated service instances in serverless environments where each invocation needs clean state
Implement a simplified CommonJS-style require() in the browser using IIFE and closures with module caching and circular dependency detection
Build a visual tool showing ESM live bindings vs CJS value copies side-by-side as values mutate in real-time