Why must export/import declarations be on top level in es2015?

╄→尐↘猪︶ㄣ 提交于 2019-11-28 09:43:49

JavaScript performs static analysis on ES6 modules. This means you cannot dynamically perform imports or exports. Read section 4.2 of this article for more information:

A module's structure being static means that you can determine imports and exports at compile time (statically) – you only have to look at the source code, you don’t have to execute it.

There are many reasons for this approach, some of which are to prepare JavaScript for future features that rely on the ability for a source file to be statically analysable, namely macros and types (discussed in the aforementioned article).

Another interesting article on this topic mentions cyclic dependencies and fast lookups as reasons.

______

If you want to perform an export within some nested block of a module, reconsider how you are writing the module and exposing its APIs/internals as it is almost certainly not necessary. The same goes for if you are currently requireing modules within nested blocks in your ES5 code. Why not require / import at the top of your module and consume their APIs/internals within the nested blocks? The main advantage of this approach, at least from a readability point of view, is that you can know the dependencies of a module without having to scan its source for require calls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!