Module.exports vs Exports Pitfall
You'll learn why reassigning exports directly doesn't work and how to avoid this common CommonJS mistake.
The Core Problem
In CommonJS, both module.exports and exports initially point to the same object. However, when a module is required, Node.js only returns module.exports.
The exports variable is just a convenient shorthand reference. If you reassign exports to something new (like a function or different object), you break that reference—but module.exports remains unchanged, so your reassignment is ignored.
Think of It Like Two Labels
Imagine module.exports and exports as two name tags on the same box. You can add items to the box using either tag:
// ✅ Works - adding properties to the shared object
exports.greet = function() { return "Hello!"; };
exports.name = "App";
But if you create a new box and put the exports tag on it, the original box (with the module.exports tag) is still what gets delivered:
// ❌ Doesn't work - breaks the reference
exports = function() { return "Hello!"; };
// module.exports still points to the empty original object
// ✅ Works - reassigns the actual export
module.exports = function() { return "Hello!"; };
When It Matters
This pitfall appears when you want to export a single function, class, or primitive value instead of an object with properties. Always use module.exports for reassignment.
Key Takeaway: Use exports.property to add properties, but use module.exports when replacing the entire export. Only module.exports determines what require() returns.