为什么必须在es2015的导出/导入声明的顶层? [英] Why must export/import declarations be on top level in es2015?

查看:482
本文介绍了为什么必须在es2015的导出/导入声明的顶层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在上一个项目中开始使用es2015与babel。当我尝试在中导入导出如果条件,我有一个错误'import'和'export'只能出现在顶层。我看到很多案例,它的效果很好, require ,但不适用于es2015模块。是否有任何理由有此限制?

解决方案

JavaScript对ES6模块执行静态分析。这意味着您不能动态地执行导入或导出。 阅读本文的第4.2节了解更多信息


模块的静态结构意味着您可以在编译时确定导入和导出(静态) - 您只需要查看源代码,你不必执行它。


这种方法有很多原因,其中一些是为将来的功能准备JavaScript它依赖于源文件的静态分析能力,即类型(在上述文章中讨论)。



另一个有趣的有关此主题的文章提及循环依赖性和快速查找作为原因。



______



如果要执行导出在模块的一些嵌套块中,重新考虑如何编写模块并公开其API /内部,因为它几乎肯定不是必需的。如果您现在在ES5代码中嵌套块中的要求模块,那么也是如此。为什么需要 / 导入在您的模块的顶部和消费他们的API /内部在嵌套块内?这种方法的主要优点是,从可读性的角度来看,您可以知道模块的依赖关系,而无需扫描其来源 require 调用。 / p>

I started using es2015 with babel in last project. When I try to do import or export inside if condition, I have an error 'import' and 'export' may only appear at the top level. I see a lot of cases for that and it works good with require, but not with es2015 modules. Is there any reason for this limitation?

解决方案

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.

这篇关于为什么必须在es2015的导出/导入声明的顶层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆