20

区别 module.exports 与 exports

 4 years ago
source link: https://blog.zfanw.com/differences-between-exports-module-dot-exports/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

既生瑜,何生亮

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

来新建一个 module.js 文件:

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

console.log(exports);

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

$ node module.js
true
{}

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

那,什么时候只能用 module.exports ?什么时候只能用 exports ?从 模块编写者 的角度出发,并没有什么区别,二者都能用;若非要说个区别,大概是 exportsmodule.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');

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK