Node.js docs' crypto module documentation uses top level await to import, but it's clearly not a dynamic import
What is the difference between the 2 statement below (they seems to do the same)
import * as fs from 'fs'
const fs_ = await import('fs'); // why use this?
[Not Duplicate]
import() imports an EC Module statically (instead of import() imports dynamically), it's very similar to the CommonJS module require() syntax, this is the only purpose of the top level await keywordSupported by: (node.js 14.8.0) (chrome 89) (Firefox 89) at the time of writing this
import * as imp from './someModule.mjs)await import('./someModule.mjs') statically requires the 'someModule' and returns its exported data as {default:'someDefVal'[, ...]} object// static import -----------------------------------// blocks this module untill './module1.mjs' is fully loaded
// traditional static import in EC modules
import * as imp from './module1.mjs';
console.log( imp ); // -> {default:'data from module-1'}
// static import with await import() (does the same as above but is prettier)
console.log( await import('./module1.mjs') ); // -> {default:'data from module-1'}
function importFn1(){ // the await import() is a satic import so cannot be used in a function body
// await import('./module1.mjs'); // this would throw a SyntaxError: Unexpected reserved word
}
// dynamic import ----------------------------------// does not block this module, the './module2.mjs' loads once this module is fully loaded (not asynchronous)
import('./module2.mjs')
.then((res)=>{ console.log(res) }) // -> {default:'data from module-2'}
.catch((err)=>{ console.log(err) });
(function ImporFn2(){
import('./module2.mjs') // dynamic import inside a function body
.then((res)=>{ console.log(res) }) // -> {default:'data from module-2'}
.catch((err)=>{ console.log(err) });
})();
console.log( '----- MAIN MODULE END -----' );
{ default: 'data from module-1' }
{ default: 'data from module-1' }
----- MAIN MODULE END -----
{ default: 'data from module-2' }
{ default: 'data from module-2' }