Junior — Middle
What is the difference between using module.exports and the exports property in Node.js when exporting modules?
sobes.tech AI
Answer from AI
In Node.js, module.exports and exports are related to module exports but work slightly differently.
module.exportsis the object that is actually returned when importing a module.exportsis simply a reference tomodule.exportsby default.
If you assign a new value to exports, the connection to module.exports is lost, and the export will not work as expected.
Example of correct usage:
// Adding properties to exports
exports.foo = function() { return 'foo'; };
// Or replacing the entire export
module.exports = function() { return 'bar'; };
If you write it like this, the export will not work:
exports = function() { return 'bar'; }; // INCORRECT
Because exports now points to a new function, but module.exports remains the same object that is exported.