How to solve this basic ES6-module circular dependency problem?
Logan Smyth
loganfsmyth at gmail.com
Thu Aug 11 00:29:23 UTC 2016
You could also swap that around to simplify the logic in the individual
classes, e.g.
```
// --- Module A
import C, {initC} from './c';
initC();
console.log('Module A', C)
class A extends C {
// ...
}
export {A as default}
```
then export that function to force-initialize the `C` variable.
```
// --- Module C
import A from './a'
import B from './b'
var C;
export function initC(){
if (C) return;
C = class C {
constructor() {
// this may run later, after all three modules are evaluated, or
// possibly never.
console.log(A)
console.log(B)
}
}
}
initC();
export {C as default};
```
So all the individual classes have to do is call the `initC` function to
ensure `C` has been properly initialized, then go from there. Note the
usage of `var` here is also critical since `let` would throw a TDZ error.
On Wed, Aug 10, 2016 at 5:04 PM, /#!/JoePea <joe at trusktr.io> wrote:
> I found a solution that works in environments compiled by Babel, using the
> [workaround suggested by Ben Newman](https://github.com/met
> eor/meteor/issues/7621#issuecomment-238992688):
>
> ```js
> // --- Module A
>
> import C from './C'
>
> let A = A // @benjamn's workaround applied
>
> export
> function setUpA(C) {
>
> A = class A extends C {
> // ...
> }
>
> }
>
> export {A as default}
> ```
>
> ```js
> // --- Module B
>
> import C from './C'
>
> let B = B // @benjamn's workaround applied
>
> export
> function setUpB(C) {
>
> B = class B extends C {
> // ...
> }
>
> }
>
> export {B as default}
> ```
>
> ```js
> // --- Module C
>
> import A, {setUpA} from './A'
> import B, {setUpB} from './B'
>
> let C = class C {
> constructor() {
> // this may run later, after all three modules are evaluated, or
> // possibly never.
> console.log(A)
> console.log(B)
> }
> }
>
> setUpA(C)
> setUpB(C)
>
> export {C as default}
> ```
>
> ```js
> // --- Entrypoint
>
> import A from './A'
> console.log('Entrypoint', new A) // runs the console.logs in the C
> constructor.
> ```
>
>
> Although that works in my environment which is compiled from ES6 modules
> to CommonJS by Babel, it [doesn't work in Rollup.js](http://goo.gl/PXXBKI),
> and may not work in other ES6 module implementations.
>
> Is there some solution that will theoretically work in any ES6 module
> environment?
>
> */#!/*JoePea
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160810/849e6fff/attachment.html>
More information about the es-discuss
mailing list