It's hard to explain so I will reproduce the code.
I have two class files.
Business.js
const Street = require("./Street");
module.exports = class Business {};
Street.js
const Business = require("./Business");
module.exports = class Street {
constructor() {
console.log(Business);
}
};
and index.js file
const Street = require("./Street");
const street = new Street();
when I run index.js (node ./index.js), it log [Function: Business] as expect,
but when I require Business.js in index.js file like below, log message change, it log empty object {}.
index.js
const Business = require("./Business");
const Street = require("./Street");
const street = new Street();
I don't understand why require Business in index.js effect log message in Street.js file.
try it out codesandbox.
Seems like there is a circular dependency. Ideally a module should not depend on a module that depend on that module.
Since your Business.js module depend on Street.js module and Street.js module depend on Business.js module (which is called a circular dependency) you are getting this "weird behavior".
Any restructure that avoid circular dependency will be okay, like moving both classes to the same file (just a suggestion, you may want to use another way as your use case and coding practices).
class Street {
constructor() {
console.log(Business);
}
}
class Business {}
module.exports = {
Street,
Business
};
try it out codesandbox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With