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

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

问题描述

我在上一个项目中开始使用 es2015 和 babel.当我尝试在 if 条件下执行 importexport 时,出现错误 'import' 和 'export' 可能只出现在顶层.我看到很多案例,它适用于 require,但不适用于 es2015 模块.这个限制有什么原因吗?

解决方案

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

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

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

另一篇有趣的文章提到循环依赖快速查找作为原因.

______

如果您想在模块的某个嵌套块中执行 export,请重新考虑如何编写模块并公开其 API/内部,因为这几乎肯定没有必要.如果您当前在 ES5 代码的嵌套块中requireing 模块,情况也是如此.为什么不在模块顶部 require/import 并在嵌套块中使用它们的 API/内部?这种方法的主要优点,至少从可读性的角度来看,是您可以知道模块的依赖关系,而无需扫描其源以进行 require 调用.

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天全站免登陆