Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I avoid circular dependency when exporting from main file to utils and back in NodeJS?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems, frist file has tree responsibilities:

  1. Defining user class
  2. Initializing user class
  3. 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,
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading