13

I was surprised to find that in Babel, I could have two modules import each other without any issues. I have found a few places that refer to this as a known and expected behaviour in Babel. I know that this is widely considered an anti-pattern by a lot of (I'm guessing most) people, but please ignore that for this question:

Does anyone know if this is (or will be) correct behaviour in ES6/7?

The closest thing I can find to an official answer (and technical explanation) is this comment on 2ality.com

Andrew
  • 14,204
  • 15
  • 60
  • 104
  • 3
    Related: [ES6 modules: imported constants are undefined at first; they become available later](http://stackoverflow.com/q/37515816/218196) – Felix Kling Nov 03 '16 at 06:51
  • 2
    Yep, it's usually considered bad practices. But ES modules are designed to support cyclic dependencies. There are some information in ES 2017 spec [15.2.1.16.3ResolveExport Concrete Method](https://tc39.github.io/ecma262/#sec-resolveexport). However, I think it's really hard to read. [This post](http://www.2ality.com/2014/09/es6-modules-final.html) might be better readable. – Leo Nov 03 '16 at 07:21
  • @Leo -- the spec you referenced (and which I blew right past in my research) is what I was looking for (though I actually linked to the that post in my question ;p). You should probably throw your comment in as an answer, because I would gladly accept it. There's no question that in OO, circ. deps are usually a footgun. But as JS drifts more toward more FP patterns, I think cross-dependent modules stop being an automatic anti-pattern. That said, OO devs need to stop shooting at their feet, so the warning will always be wise. – Andrew Nov 03 '16 at 08:47
  • @FelixKling -- Thanks for that. I used to do all JS in require.js, which forced you to deal with your own circular dependencies by hand (shim a cross-dependency and then re-resolve later it after everything was loaded, if I remember correctly). But if I read the spec right (thanks to @Leo), it looks like that initial 'undefined' resolution will (eventually) no longer exist (except in polyfills). Actual language support will be amazing. – Andrew Nov 03 '16 at 08:59

2 Answers2

7

It's usually considered bad practices. But ES modules are designed to support cyclic dependencies. There are some information in ES 2017 spec 15.2.1.16.3ResolveExport Concrete Method. However, I think it's really hard to read (to be honest, I suffer a lot). The post you mentioned from 2ality.com might be better readable.

Leo
  • 13,428
  • 5
  • 43
  • 61
2

I work with nodeJS, so it's kinda the same. From what I know, "require cycles" are not illegal, even if it's often best to avoid them. If there is a cycle, nodeJS at least will handle that: it will not require the second time.

Ludwik
  • 2,247
  • 2
  • 27
  • 45