在CommonJS规范中,有两种导出模块API的方式,分别为module.exports和exports。
这两个变量默认都指向同一个初始值{}。
module.exports导出模块API的例子:
const a = 1; const b = 2; const c = () => a + b; module.exports = { a, b, c };
使用exports导出模块API:
exports.a = 1; exports.b = 2; exports.c = () => a + b;
但是这两种用法不能混用,因为“module.exports = 新对象”改写了module.exports的默认引用,而引擎默认返回的是module.exports,这将导致exports指向的初始空间无效了。这样一来,原先用exports导出的那些数据就不会被导出了。
下面这是个反面示例:
exports.a = 1; exports.b = 2; exports.c = () => a + b; const d = 'foobar' module.exports = {d}
上面代码只导出了d,而没有导出a、b、c,因为module.export = { d }覆盖了默认的初始空间,导致之前exports变量上增加的属性(a、b、c)不会被导出。
我们应该尽量去用module.exports,少去用“exports.属性名 =” 这种写法。
CommonJS规范有1、2两个版本,exports.属性名 = …属于CommonJS1的用法。
而module.exports属于CommonJS2的用法。