Skip to content

Javascript – Where are ‘import’ and ‘export’ statements legal?

I’m studying the new import, export feature in Javascript but was wondering, where in code will these statements be syntactically legal?

I understand something like the following won’t be legal:

    import thing from './thing.js';

but does this mean import is only legal at the top of the module script? Or in the global scope? E.g., what about this:

import a from './a.js';
    // ... do something with a ...
import b from './b.js';
// ...

Also, does this limitation apply to export? E.g., will the following be legal?

    function internalFunc() {
        // ...
    export { internalFunc };

I couldn’t seem to find anything about this in the current drafts of the specification.


My reading of the spec is that:

  • module export statements should be at top level of a module

  • module import statements should be at top level of a module

  • function-style module import expressions (which return a promise for the imported items) are allowed anywhere an expression is allowed

As you say, right now it’s only supported in transpilers, so I’m not sure how closely existing transpilers (Babel) follow these rules.