0

I have 2 javascript files:

In first.js:

const { number } = require('./second.js');

const numEnum = {
  NUM1: 5,
  NUM2: 10
}
const useNumber = () => {
  console.log('The chosen num is:' chosenNum.numberVal);
}

module.exports = {
  numEnum 
};

And in second.js

const { numEnum } = require('./first.js');

const chosenNum = {
  numberVal: numEnum.NUM1
}

module.exports = {
  chosenNum 
};

But there's a loop. The first file needs the export from the second file which uses the first file.

How should I solve it? Is there a way besides using a third file?

Poogy
  • 2,597
  • 7
  • 20
  • 35
  • 2
    It's a very old joke: "- Doctor it hurts when I do THIS. - The don't DO that!" – Scott Sauyet Apr 11 '18 at 18:23
  • 3
    I would start by reading the nodejs docs. It amazes me that people try to use things without even bothering to read the documentation on them. Your "problem" is verbatim from the nodejs module documentation. Specifically the part on [Cycles](https://nodejs.org/api/modules.html#modules_cycles) – gforce301 Apr 11 '18 at 18:24
  • 1
    There are 2 known solutions `1. Don't have circular dependencies` or `2. Reorder your require and export statements`. I would choose solution 1. – Xotic750 Apr 11 '18 at 18:27
  • 1
    Sorry, there is also `3. Dependency Injection` and some other even more complex solutions. – Xotic750 Apr 11 '18 at 18:31
  • 1
    There is even a 6 year old question about it here on SO https://stackoverflow.com/questions/10869276/how-to-deal-with-cyclic-dependencies-in-node-js – Xotic750 Apr 11 '18 at 18:34

0 Answers0