How to solve this basic ES6-module circular dependency problem?
/#!/JoePea
joe at trusktr.io
Fri Aug 12 08:07:28 UTC 2016
> Every time you access `foo` in the second module, you are literally
reaching into the first module to grab the current value of `foo`.
Exactly! So, that means that in theory, I should be able to remove the `C`
parameters from my `setUpA` and `setUpB` functions in my [last example](
https://esdiscuss.org/topic/how-to-solve-this-basic-es6-module-circular-dependency-problem#content-23),
so it becomes the following (but it doesn't work in some Babel environments
(Meteor, Webpack) or Rollup).
```js
// --- Entrypoint
import A from './A'
console.log('Entrypoint', new A)
```
```js
// --- Module A
import C from './C'
import {setUpB} from './B'
let A
export
function setUpA() {
if (!A) {
A = class A extends C {
// ...
}
}
}
if (setUpA && C) setUpA()
if (setUpB && C) setUpB()
export {A as default}
```
```js
// --- Module B
import C from './C'
import {setUpA} from './A'
let B
export
function setUpB() {
if (!B) {
B = class B extends C {
// ...
}
}
}
if (setUpA && C) setUpA()
if (setUpB && C) setUpB()
export {B as default}
```
```js
// --- Module C
import A, {setUpA} from './A'
import B, {setUpB} from './B'
class C {
constructor() {
// this may run later, after all three modules are evaluated, or
// possibly never.
console.log(A)
console.log(B)
}
}
if (setUpA && C) setUpA()
if (setUpB && C) setUpB()
export {C as default}
```
I found that with Ben Newman's deferred imports idea, the problem literally
goes away:
```js
// --- Entrypoint
import A from './A'
console.log('Entrypoint', new A)
```
```js
// --- Module A
import C from './C'
class A extends C {
// ...
}
export {A as default}
```
```js
// --- Module B
import C from './C'
class B extends C {
// ...
}
export {B as default}
```
```js
// --- Module C
class C {
constructor() {
// this may run later, after all three modules are evaluated, or
// possibly never.
// reach into the A and B modules
import A from './A'
import B from './B'
console.log(A)
console.log(B)
}
}
export {C as default}
```
*/#!/*JoePea
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160812/c610c4bc/attachment.html>
More information about the es-discuss
mailing list