导入ESM模块时await关键字的作用是什么

What is the await keyword effect when importing ESM modules

Node.js docs的加密模块文档使用顶级await导入,但显然不是动态导入

来源: https://nodejs.org/dist/latest-v15.x/docs/api/crypto.html#crypto_static_method_certificate_exportchallenge_spkac_encoding

下面2个说法有什么区别(好像是一样的)

import * as fs from 'fs'
const fs_ = await import('fs');        // why use this?

[不重复]

  • await import()静态导入一个EC模块(而不是import()动态导入),它与CommonJS模块require()语法非常相似,这是唯一的目的顶级 await 关键字

在撰写本文时支持:(node.js 14.8.0) (chrome 89) (Firefox 89)

  • 那么,如果我们已经拥有所有这些漂亮的静态导入语法,为什么还要使用它呢? (比如:import * as imp from './someModule.mjs
  • 嗯,它写起来更简单,也更容易记住(例如:await import('./someModule.mjs') 静态需要 'someModule' 和 returns 其导出数据作为 {default:'someDefVal'[, ...]} 对象
// 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' }