I know that in the new ES6 module syntax, the JavaScript engine will not have to evaluate the code to know about all the imports/exports, it will only parse it and “know” what to load.
This sounds like hoisting. Are the ES6 modules hoisted? And if so, will they all be loaded before running the code?
Is this code possible?
import myFunc1 from 'externalModule1'; myFunc2(); if (Math.random()>0.5) { import myFunc2 from 'externalModule2'; }
ES6 module loaders will be asynchronous while node.
ES6 modules are automatically strict-mode code, even if you don't write "use strict"; in them. You can use import and export in modules.
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.
If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used. If a module is imported multiple times, but with the same specifier (i.e. path), the JavaScript specification guarantees that you'll receive the same module instance.
After doing some more research, I've found:
This code will have no errors, and will work:
localFunc(); import {myFunc1} from 'mymodule'; function localFunc() { // localFunc is hoisted myFunc1(); }
It will be a SyntaxError. According to this part of specification:
Module : ModuleBody ModuleBody : ModuleItemList ModuleItemList : ModuleItem ModuleItemList ModuleItem ModuleItem : ImportDeclaration ExportDeclaration StatementListItem
It means that module can contain only ImportDeclaration
's, ExportDeclaration
's or StatementListItem
's. According to this StatementListItem
could not contain ImportDeclaration
nor ExportDeclaration
.
import myFunc1 from 'externalModule1';
is an import declaration, while:
if (Math.random()>0.5) { import myFunc2 from 'externalModule2'; }
is a statement. So your code will result to a syntax error.
What about "will they all be loaded before running the code?". This part of specification contain next sentence:
NOTE: Before instantiating a module, all of the modules it requested must be available.
So, yeah. They will all be loaded before running the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With