思考一下nodejs的exports和module.exports

  张一帆   2016年12月12日


之前看nodejs的书籍的时候,书上来就会讲nodejs的结构同时也会带出exports和module.exports这两个词语。起初,知识想快速学习nodejs开发技巧并且能够达到上手的效果。但是,在写代码和研究代码的时候我发现有的js文件后面使用exports,而有的却用的是module.exports。经过,代码的测试发现这两个词语效果是一样的。那么我就会想既然他们俩的效果是一样的话,那为什么还要出两种方案呢?

后来,查阅了一下nodejs的官方参考手册,其中里面就有讲到:

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. 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是一样的,很多人都归结为exports是module.exports的引用。如果你不清楚引用是什么概念,请你看看那这篇文章,这篇文章用一个例子给你举出了他们俩的区别。但是,我对这位作者的回答不算太满意。于是我又追到了这篇文章。但是,我又对作者给出的结论感到迷茫。作者说“如果你想你的模块是一个特定的类型就用Module.exports。如果你想的模块是一个典型的“实例化对象”就用exports。”,我就不是很懂他说的这两种情况。

对于目前我的理解来说,我就是认为exports是module.exports的简写。但是这是有条件的,条件就是module.exports定义之后不能对exports操作。