Search code examples
javascriptwebpackcircular-dependencyes6-modules

Webpack ES6 modules circular dependencies when using index files


I have a big project, I try to refactor to ES6 modules right now.

To make further development easier, I wanted to introduce index files, which just export all modules within the directory:

index.js:

export { default as ModuleA } from './moduleA'
export { default as ModuleB } from './moduleB'
export { default as ModuleC } from './moduleC'

moduleA.js:

import { ModuleB } from './index'

moduleB.js:

import { ModuleC } from './index'

ModuleC.doSomething()

moduleC.js:

export default {
  doSomething: () => {}
}

Starting point is ModuleA.

The problem is, that in ModuleB ModuleC is undefined, so doSomething can't be executed.
I suspect some issues with circular dependencies, since moduleB tries to access the index again, which parses moduleB before moduleC.

Is it just not possible to do this, or is there another solution?


Solution

  • The issue here is that ModuleC has not been exported by the time that ModuleB is exported and runs, and since ModuleC is a requirement of ModuleB, it can't run. If I were you, I would just export each of them from their own files, and when you import them, import them from their own files instead of index.js.

    Example

    ModuleA.js:

    import { ModuleB } from 'moduleB.js'
        export default {
          // Your code here
    }
    

    ModuleB.js

    import { ModuleC } from 'moduleC.js'
    moduleC.doSomething();
    

    ModuleC.js

    export default {
        doSomething: () => {
          // Your code
        }
    }
    

    And finally, since ModuleA is the entry point from index.js, just import it into index.js and run what you need to run.