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

์ž‘์„ฑ์ž

์นดํ…Œ๊ณ ๋ฆฌ:

โ† ํ”ผ๋“œ๋กœ
DEV Community ยท Krati Joshi ยท 2026-07-25 ๊ฐœ๋ฐœ(SW)

Krati Joshi

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

์›๋ฌธ์—์„œ ๊ณ„์† โ†—

์ถ”์ถœ ๋ณธ๋ฌธ ยท ์ถœ์ฒ˜: dev.to ยท https://dev.to/joshikrati03/backend-internals-4-exports-vs-moduleexports-whats-the-difference-5740

์ฝ”๋ฉ˜ํŠธ

๋‹ต๊ธ€ ๋‚จ๊ธฐ๊ธฐ

์ด๋ฉ”์ผ ์ฃผ์†Œ๋Š” ๊ณต๊ฐœ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ํ•„์ˆ˜ ํ•„๋“œ๋Š” *๋กœ ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค