最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why must exportimport declarations be on top level in es2015? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Dec 25, 2015 at 9:16 Kirill Fuchs 13.7k4 gold badges43 silver badges73 bronze badges asked Dec 10, 2015 at 13:36 Alexandr SubbotinAlexandr Subbotin 1,7342 gold badges17 silver badges16 bronze badges 2
  • 2 Because es2015 modules are synchronously loaded maybe? Allowing nested exports would mean that the export may be deferred until that line is called – CodingIntrigue Commented Dec 10, 2015 at 13:50
  • babel-eslint. stackoverflow.com/questions/39158552/… – chetan pawar Commented Jul 6, 2017 at 23:24
Add a comment  | 

1 Answer 1

Reset to default 17

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.


This is tangential to the direct question asked, but if it suits your use case, you can of course use a dynamic import within your if block like so:

if(foo) {
  let bar = await import("./bar.js");
  // ...
}
发布评论

评论列表(0)

  1. 暂无评论