Node.js module.exports
的用途是什么,你是如何使用它的?
我似乎找不到任何关于此的信息,但它似乎是 Node.js 的一个相当重要的部分,因为我经常在源代码中看到它。
module
A reference to the current
module
. In particularmodule.exports
is the same as the exports object. Seesrc/node.js
for more information.
但这并没有真正的帮助。
module.exports
究竟做了什么,一个简单的例子是什么?
最佳答案
module.exports
是作为 require
调用的结果实际返回的对象。
exports
变量最初设置为同一个对象(即,它是简写“别名”),因此在模块代码中您通常会这样编写:
let myFunc1 = function() { ... };
let myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;
导出(或“公开”)内部作用域函数 myFunc1
和 myFunc2
。
在调用代码中你会使用:
const m = require('./mymodule');
m.myFunc1();
最后一行显示 require
的结果如何(通常)只是一个可以访问其属性的普通对象。
注意:如果您覆盖 exports
,那么它将不再引用 module.exports
。因此,如果您希望将新对象(或函数引用)分配给 exports
,那么您还应该将该新对象分配给 module.exports
值得注意的是,添加到 exports
对象的名称不必与要添加的值的模块内部范围名称相同,因此您可以:
let myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required
接着是:
const m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName
关于javascript - Node.js module.exports 的用途是什么,你如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5311334/