简体   繁体   中英

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? Eg, 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 ? Eg, 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.

There is no such implementation in javascript. It's planned. But no browser implemented it yet. It's implemented in some transpilers like Webpack and Babel. There is also require in NodeJs. But not natively in javascript. Other way to import files is using RequireJS library.

Reference: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/import

Edit

Answering what you asked in comments: AFAIU in the already available implementations of import and export, yes they are available in the global space, and yes import and export are hoisted. But what isn't very clear in your comment's question is what you mean by "only available in global space". There is no such this as a close space that can't acess global space. Global space is accessible everywhere, so are import and export.

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.

1) If you want just to play with import , export statements, then use it without any transpilation (with webpack) in google chrome ;)

I always use ES6 modules while I make some R&D. And then only if my temporarily work worth it, I start to think about transpilation.

Just do not forget to include scripts in such way:

<script type="module" src="index.js"></script>

2) If you need to write some nodejs script, then turn on some experimental flag to use modules - https://nodejs.org/api/esm.html#esm_enabling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM