0

I'm writing an express app in ES6 and the file structure I am using is grouping files by functionality. Each module has an index.js which is responsible for exporting any relevant methods, classes, etc. Other sibling modules only require the index.js from another module.

However I have run into an issue with circular dependencies. For instance I have a User module that exports:

export routes from './routes';
export default from './User'; //model
export helpers from './helpers';

Then I have another model Session that does something similar:

export routes from './routes';
export helpers from './helpers';

The issue is that session/routes uses something from user/helpers and user/routes uses something from session/helpers. The importing in session/routers is import {helpers} from '../user. And the import in user/routers is import {helpers} from '../session'

This results in a circular dependency between the two modules via their respective index.js files.

This causes problems because sometimes when I import the package in some third module, it is empty on the first tick.

Other than the obvious solution of not including routes as an export in both module's index.js, is there another solution to dealing with this?

wlingke
  • 4,699
  • 4
  • 36
  • 52
  • Why don't you simply `import helpers from '../…/helpers'`? – Bergi Oct 18 '16 at 00:56
  • @Bergi That breaks the idea of modules not having to know about internals of other modules. Probably a less ideal solution than just excluding routes from the exports =\ – wlingke Oct 18 '16 at 04:40
  • I don't see what's internal about a module name? I'd consider those 5 separate modules (+2 for bundling). If you only have 2 (top-level) modules, you cannot avoid the circular dependency. – Bergi Oct 18 '16 at 11:10

1 Answers1

0

It is always difficult to manage dependencies and run into this problem. The obvious solution that you suggest is the best one as well but try to find out pieces that need to be decoupled and to create new modules to accommodate this.

The other solution that I would suggest is to use a module that will resolve the dependencies for you and it will notify you on the boot of the app that you have circular dependency issue and will not boot the application at all. I don't know how big your project is but if is big then it will be very difficult to plug such a module in. You can have a look at the following modules:

Stavros Zavrakas
  • 3,045
  • 1
  • 17
  • 30