javascript 为什么必须在 es2015 中将导出/导入声明置于顶层?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34203325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:22:44  来源:igfitidea点击:

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

javascriptecmascript-6babeljses2015

提问by Alexandr Subbotin

I started using es2015 with babel in last project. When I try to do importor exportinside ifcondition, 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?

我在上一个项目中开始使用 es2015 和 babel。当我尝试执行importexport内部if条件时,出现错误'import' and 'export' may only appear at the top level。我看到很多案例,它适用require于 es2015 模块,但不适用于 es2015 模块。这个限制有什么原因吗?

回答by sdgluck

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:

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

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 macrosand types(discussed in the aforementioned article).

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

Another interesting article on this topicmentions cyclic dependenciesand fast lookupsas reasons.

关于这个主题的一篇有趣的 文章提到了循环依赖快速查找的原因。

______

______

If you want to perform an exportwithin 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/ importat the top of your module and consumetheir 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 requirecalls.

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