在 Node 中,每个模块内部都有一个自己的 module 对象;该 module 对象中,有一个成员叫:exports 对象,默认是一个空对象;
也就是说,如果需要对外导出成员,只需要把导出的成员挂载到 module.exports 中;谁来 require 该文件,谁就得到 module.exports。
在每个模块中都默认存在:
console.log(exports === module.exports) // true
Node 为了简化操作,专门提供了一个变量: exports = module.exports
;
所以说:模块中还有一句代码: var exports = module.exports
,可以使用任意一方来导出成员
但是:默认在代码的最后一句:return module.exports
; 最终导出的还是 module.exports
当一个模块需要导出单个成员时,直接给 exports
赋值时无效的,因为导出单一成员时,是直接给module.exports
赋值;此时 expors
丢失了对 module.exports
的引用,所以再对 exports
进行单独赋值 ,也不能被导出了。
真正使用的时候:
导出多个成员:exports.abc = xxx
或者: module.exports = {abc : xxx, xyz = xxx}
导出单个成员:module.exports = xxx
为了防止出现对两者引用的混乱,可以当作exports
不存在,永远都只使用module.exports