Node.js exports vs module.exports: A Key Difference Every Developer Should Know
In Node.js, both exports and module.exports are used to share code between files, but they are not fully interchangeable. When Node.js executes a file, exports is initialized as a reference to module.exports, meaning adding properties to exports works correctly. However, directly reassigning exports — such as exports = MyClass — breaks that reference, leaving module.exports pointing to the original empty object, which is what require() ultimately returns. This is why require() can unexpectedly return an empty object when developers attempt to export a single function or class using exports. To safely export a single value, developers should always use module.exports directly, while exports can be used reliably for adding multiple named properties.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in