exports 快捷方式
【exports shortcut】
exports 变量在模块的文件级作用域内可用,并且在模块被评估之前,它被赋值为 module.exports 的值。
【The exports variable is available within a module's file-level scope, and is
assigned the value of module.exports before the module is evaluated.】
它允许使用快捷方式,因此 module.exports.f = ... 可以更简洁地写作 exports.f = ...。但是,需要注意的是,和任何变量一样,如果给 exports 赋予一个新值,它将不再与 module.exports 绑定:
【It allows a shortcut, so that module.exports.f = ... can be written more
succinctly as exports.f = .... However, be aware that like any variable, if a
new value is assigned to exports, it is no longer bound to module.exports:】
module.exports.hello = true; // Exported from require of module
exports = { hello: false }; // Not exported, only available in the module 当 module.exports 属性被一个新对象完全替换时,通常也会重新赋值 exports:
【When the module.exports property is being completely replaced by a new
object, it is common to also reassign exports:】
module.exports = exports = function Constructor() {
// ... etc.
}; 为了说明这种行为,想象一下这个假设的 require() 实现,它与 require() 实际上所做的事情非常相似:
【To illustrate the behavior, imagine this hypothetical implementation of
require(), which is quite similar to what is actually done by require():】
function require(/* ... */) {
const module = { exports: {} };
((module, exports) => {
// Module code here. In this example, define a function.
function someFunc() {}
exports = someFunc;
// At this point, exports is no longer a shortcut to module.exports, and
// this module will still export an empty default object.
module.exports = someFunc;
// At this point, the module will now export someFunc, instead of the
// default object.
})(module, module.exports);
return module.exports;
}