What is the difference between module.exports and exports in CommonJS?
exports is just a shortcut variable pointing at module.exports. You can add properties to either, but only module.exports is what require returns, so reassigning exports alone exports nothing.
Explain it simply
Picture a courier who delivers only the parcel in his left hand, called module.exports. Node also gives you a second name, exports, which points at the same parcel. As long as both names point at the same parcel, adding things through either works. The moment you point exports at a brand-new parcel, the courier still carries the old one.
Example
// works: adds a property to the shared object
exports.add = (a, b) => a + b;
// works: replaces the whole export
module.exports = function greet(name) {
return "Namaste " + name;
};
// broken: exports now points somewhere else, require() never sees it
exports = { add: (a, b) => a + b };Behind the scenes Node starts every file with exports = module.exports = {}, and require always returns module.exports.
What to say in the interview
"exports is a reference to module.exports. Adding properties to exports works, but assigning to exports breaks the link, and require only returns module.exports. If I want to export a single function or class, I assign it to module.exports directly."
Common mistakes
- Writing
exports = somethingand wondering whyrequirereturns an empty object. - Mixing both styles in one file, so the later
module.exports =silently discards earlierexports.xlines.