Skip to content
Advertisement

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:

(function(){

    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';

(function(){

    // ... do something with a ...

})();

import b from './b.js';

// ...

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

(function(){

    function internalFunc() {
        // ...
    }

    export { internalFunc };

})();

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement