I have a constructor that I initialize in my main Javascript file that we will call main.js and then I have a separate file called: utils.js, in utils I will just print the name in a function and export back the function to the main file but it gives me circular dependency warning and returns undefined:
const { test } = require("./utils");
class User {
constructor(name) {
this.name = name;
}
}
const user = new User({
name: "Oscar",
});
console.log("Your name is: %s!", user.name); // Outputs: { name: 'Oscar' }
test() // This gives me undefined and also circular dependency warning
module.exports = {
user,
};
And then in the utils file I want to simply do:
const { user } = require("./main");
const test = () => {
console.log("Hello there %s!", user.name);
};
module.exports = {
test,
}
How can I export back test function to main and avoid having circular dependency issues?
>Solution :
It seems, frist file has tree responsibilities:
- Defining user class
- Initializing user class
- Making something with user
So, good practice is to separate them.
main.js
const { test } = require("./utils");
const { user } = require("./create-user");
console.log("Your name is: %s!", user.name); // Outputs: { name: 'Oscar' }
test() // This gives me undefined and also circular dependency warning
module.exports = {
user,
};
create-user.js
const { User } = require("./user");
const user = new User({
name: "Oscar",
});
module.exports = {
user,
};
user.js
class User {
constructor(name) {
this.name = name;
}
}
module.exports = {
User,
};
utils.js
const { user } = require("./create-user");
const test = () => {
console.log("Hello there %s!", user.name);
};
module.exports = {
test,
}