module.exports์™€ exports

module.exports์™€ exports

Front-end developer WONISM
Interested in ReactJS, RxJS and ReasonML.

module์€ exports์†์„ฑ์ด ์žˆ๋Š” ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐ์ฒด์ด๋ฉฐ, exports๋Š” ๋ณดํ†ต module.exports๋กœ ์„ค์ •๋˜๋Š” ์ผ๋ฐ˜์ ์ธ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๋ณ€์ˆ˜์ด๋‹ค.
exports.a = 42;์™€ ๊ฐ™์ด exports์˜ ์†์„ฑ์„ ์„ค์ •ํ•˜๋ฉด, module.exports.a๋„ ์„ค์ •์ด ๋œ๋‹ค. ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” ๊ฐ์ฒด๊ฐ€ ์ฐธ์กฐ๋กœ ์ „๋‹ฌ๋˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.
์ฆ‰, exports์™€ module.exports๋Š” ๊ฐ™์€ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ•˜๋ฉฐ, this ๋˜ํ•œ ๋งˆ์ฐฌ๊ฐ€์ง€์ด๋‹ค.
๋‹ค์Œ๊ณผ ๊ฐ™์€ ์˜ˆ์ œ๋ฅผ ํ†ตํ•ด ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

# write file with printf
$ printf "// module.exports\nmodule.exports.add = function (a, b) { return a + b; };\n\n// exports\nexports.add = function (a, b) { return a + b; };\n\n// this\nthis.add = function (a, b) { return a + b; };" > math.js

# execute node.js
$ node

> const math = require('./math');
undefined
> math
{ add: [Function] }
> math.add(42, 5);
47