问题描述
我在上一个项目中开始使用es2015与babel。当我尝试在中导入
或导出
内如果
条件,我有一个错误'import'和'export'只能出现在顶层
。我看到很多案例,它的效果很好, require
,但不适用于es2015模块。是否有任何理由有此限制?
JavaScript对ES6模块执行静态分析。这意味着您不能动态地执行导入或导出。 :
这种方法有很多原因,其中一些是为将来的功能准备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:
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 require
ing 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的导出/导入声明的顶层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!