The difference between module.exports and exports

4 篇文章 0 订阅

There is no magic. Your module code is sandwiched between the two items in this array, and eval’d:

NativeModule.wrapper = [
  '(function (exports, require, module, __filename, __dirname) { ',
'\n});'
];

https://github.com/joyent

The magic variables you can use in modules - exportsrequiremodule__filename, and __dirname are not magic, they are just parameters to the function that is invoked when your module is loaded.

Initially, exports and module.exports point at the same empty object.

You can add properties to this object using either module.exports or exports since they both point to the same object, it doesn’t matter which you use.

If you add exports.foo = "bar" and module.exports.baz = "boz" then your module’s exported object will look like:

{foo: "bar", baz: "boz"}

…but, what if you want to export a function, or a string, or a unicorn?

This is when the difference between exports and module.exports is important.

If you remember nothing else from this article, remember this:

module.exports wins

What this means is that whatever object module.exports is assigned to is the object that is exported from your module.

If you want to export a function from your module and you assign it to exports and not module.exports then this happens:

Ruh roh! Your module will export an empty object, not the function that you probably intended it to export!

If you want to export something other than an empty object and you want to use exports elsewhere in your module, you’ll need to reassign them both:

exports = module.exports = function () {/* ... */}
exports.foo = "bar"

…and that’s it. Simple.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值