Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 320
Alexandr Subbotin Avatar asked Dec 10 '15 13:12

Alexandr Subbotin


People also ask

What is the difference between require and import keyword?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with .

What is import in ES6?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.


1 Answers

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.

like image 95
sdgluck Avatar answered Oct 04 '22 11:10

sdgluck