TL;博士
只需使用exports.someMember = someMember而不是module.exports = { // new object }.
扩展答案
在阅读了 lanzz 的回复后,我终于可以弄清楚这里发生了什么,所以我会在这个问题上给我两分钱,扩展他的答案。
让我们看看这个例子:
一个.js
console.log("a starting");
console.log("a requires b");
const b = require("./b");
console.log("a gets b =", b);
function functionA() {
console.log("function a");
}
console.log("a done");
exports.functionA = functionA;
b.js
console.log("b starting");
console.log("b requires a");
const a = require("./a");
console.log("b gets a =", a);
function functionB() {
console.log("On b, a =", a)
}
console.log("b done");
exports.functionB = functionB;
main.js
const a = require("./a");
const b = require("./b");
b.functionB()
输出
a starting
a requires b
b starting
b requires a
b gets a = {}
b done
a gets b = { functionB: [Function: functionB] }
a done
On b, a = { functionA: [Function: functionA] }
在这里我们可以看到,首先b接收一个空对象 as a,然后一旦a完全加载,该引用就会通过 更新exports.functionA = functionA。如果您将整个模块替换为另一个对象,通过module.exports,那么b将丢失来自 的引用a,因为它将从一开始就指向同一个空对象,而不是指向新对象。
因此,如果您a像这样导出:module.exports = { functionA: functionA },那么输出将是:
a starting
a requires b
b starting
b requires a
b gets a = {}
b done
a gets b = { functionB: [Function: functionB] }
a done
On b, a = {} // same empty object