区别 module.exports 与 exports

摘要:Node.js 模块里,我们经常见着 module.exports 与 exports 。二者区别在哪?那,什么时候只能用 module.exports ?什么时候只能用 exports ?从 模块编写者 的角度出发,并没有什么区别,二者都能用;若非要说个区别

既生瑜,何生亮

Node.js 模块里,我们经常见着 module.exports 与 exports 。二者区别在哪?

来新建一个 module.js 文件:

console.log(exports === module.exports);

console.log(exports);

然后在命令行下运行 node module.js :

$ node module.js
true
{}

=== 判断结果为 true 。这说明二者是一样的,指向同一个空对象 {} 。

那,什么时候只能用 module.exports ?什么时候只能用 exports ?从 模块编写者 的角度出发,并没有什么区别,二者都能用;若非要说个区别,大概是 exports 比 module.exports 少打 7 个字符,省点时间:

exports.pi = 3.14
// vs
module.exports.pi = 3.14

但是从模块使用者角度说,则二者是有区别的。


不具名数据

假设我作为模块使用者,要在我的代码中导入一个函数:

const func = require('./module');

则编写者只能使用 module.exports 来定义:

module.exports = function () {}

如果编写者使用 exports 来定义:

exports.func = function () {}

则使用者必须知道该函数的名称才能使用:

const { func } = require('./module');

把函数换成变量、常量或其它,也是一样道理。

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_7471