node.js中的module.exports和exports

之前对exportsmodule.exports一直存在疑惑,知道exports使用不当可能会导致问题,所以一直使用module.exports, 理解没有深入。通过阅读官方文档,对它们的区别、联系和使用注意事项做一个总结。

翻译自官方文档

官方文档
在node每个模块中,都有一个module变量保存着对当前模块的引用。为了方便,module.exports也可以通过exports全局模块来访问。module不是全局的,对每一个模块来说,它都是一个本地变量。

module.exports

module.exports对象,是由模块系统创建的。当你想在其他类中引用一个模块时,可以用它来实现,通过将你要导出的对象赋值给module.exports。千万注意,本地的exports对象仅仅在初始的时候保存着对module.exports的引用,有些时候可能不会得到你想要的结果。
举个例子来说,创建一个a.js的模块:

const EventEmitter = require('events');
module.exports = new EventEmitter();
// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(() => {
module.exports.emit('ready');
}, 1000);

然后在另一个模块,我们可以引入它:

const a = require('./a');
a.on('ready', () => {
console.log('module "a" is ready');
});

请注意,对module.exports的复制必须是立即执行的,不可以在任何回调中进行导出。比如,下面这样无效:

setTimeout(() => {
module.exports = { a: 'hello' };
}, 0);

exports shortcut

exports变量仅在模块的文件作用域内有效,在初始时,它保存着对module.exports的应用。所以有些时候,module.exports.f = ...可以简写为exports.f = ....。但是,千万注意,在对它进行重新赋值之后,它将不再绑定到module.exports

module.exports.hello = true; // Exported from require of module
exports = { hello: false }; // Not exported, only available in the module

当对module.exports重新赋值为新对象的时候,最好把exports也重新赋值

module.exports = exports = function Constructor() {
// ... etc.
};

require实现

为了更好的解释这一点,下面是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;
}

总结

  • 在一个模块内,exports仅仅是对module.exports的引用
  • 在未对exports重新赋值前,可以使用exports.myfun=function(){}的形式导出,但请不要使用exports = { } 的形式
  • 整对象导出时,尽量使用module.exports=exports= function Constructor(){ }的形式,避免出现漏洞