Node.js中exports,module.exports以及require方法

在Node.js中,使用module.exports.f = ...与使用exports.f = ...是一样的,此时exports就是module.exports的一种简写方式。但是,需要注意的是,如果直接给exports赋值的话,exports就与module.exports没有任何关联了,比如:

exports = { hello: false };  // Not exported, only available in the module

此时,exports是没有导出任何变量的。

要弄清楚之所以会发生这种事情,可以看一下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;
}

从代码中可以看到,在module文件里面的exports变量,实际上就是module.exports,如果在module文件里面给exports变量赋值了,那么exports变量就指向了其他对象,而require方法返回的是module.exports。上面的代码可以用下图表示:

参考链接:

https://nodejs.org/api/modules.html#modules_the_module_wrapper

原文地址:https://www.cnblogs.com/chaoguo1234/p/9827424.html