DEV Community

Krati Joshi
Krati Joshi

Posted on

πŸš€ Backend Internals #4: exports vs module.exports β€” What's the Difference?

Most Node.js beginners think these are interchangeable:

exports.sayHi = () => console.log("Hi");
Enter fullscreen mode Exit fullscreen mode
module.exports = () => console.log("Hi");
Enter fullscreen mode Exit fullscreen mode

But there's one important difference that can leave you scratching your head when require() suddenly returns {}.

The hidden truth

When Node.js runs your file, it creates something like this:

(function (exports, require, module) {
  // Your code
});
Enter fullscreen mode Exit fullscreen mode

At the beginning:

exports === module.exports // true
Enter fullscreen mode Exit fullscreen mode

So this works:

exports.add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

because you're adding a property to module.exports.

The common mistake

exports = function () {
  console.log("Hello");
};
Enter fullscreen mode Exit fullscreen mode

This doesn't export your function.

Why?

Because you've only changed the local exports variable. module.exports still points to the original empty object, and that's what require() returns.

Rule to remember

βœ… Export multiple values:

exports.add = add;
exports.sub = sub;
Enter fullscreen mode Exit fullscreen mode

βœ… Export one function, class, or object:

module.exports = MyClass;
Enter fullscreen mode Exit fullscreen mode

❌ Never do:

exports = MyClass;
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Takeaway

  • exports is just a shortcut to module.exports.
  • Adding properties is fine.
  • Reassigning exports breaks the connection.
  • For single exports, always use module.exports.

Have you ever been confused by require() returning {}? Now you know why.

#NodeJS #JavaScript #Backend #WebDevelopment #Programming

Top comments (0)