TL; DR
exports.someMember = someMember
の代わりに使用してmodule.exports = { // new object }
ください。
拡張回答
lanzzの回答を読んだ後、私はついにここで何が起こっているのかを理解することができたので、私はこの主題について2セントを与え、彼の回答を拡張します。
この例を見てみましょう:
a.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
は空のオブジェクトをとして受け取り、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