module.exports
is the object that's actually returned as the result of a require
call.
(module.exports
是由于require
调用而实际返回的对象。)
The exports
variable is initially set to that same object (ie it's a shorthand "alias"), so in the module code you would usually write something like this:
(最初, exports
变量设置为相同的对象(即,它是“ alias”的简写),因此在模块代码中,您通常会编写如下代码:)
let myFunc1 = function() { ... };
let myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;
to export (or "expose") the internally scoped functions myFunc1
and myFunc2
.
(导出(或“暴露”)内部作用域函数myFunc1
和myFunc2
。)
And in the calling code you would use:
(在调用代码中,您将使用:)
const m = require('./mymodule');
m.myFunc1();
where the last line shows how the result of require
is (usually) just a plain object whose properties may be accessed.
(最后一行显示require
的结果(通常)只是一个可以访问其属性的普通对象。)
NB: if you overwrite exports
then it will no longer refer to module.exports
.
(注意:如果您覆盖exports
则它将不再引用module.exports
。)
So if you wish to assign a new object (or a function reference) to exports
then you should also assign that new object to module.exports
(因此,如果您希望为exports
分配一个新对象(或函数引用),则还应该将该新对象分配给module.exports
)
It's worth noting that the name added to the exports
object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:
(值得注意的是,添加到exports
对象的名称不必与要添加的值的模块内部作用域名称相同,因此您可以:)
let myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required
followed by:
(其次是:)
const m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…