微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

Node.js 文档的加密模块文档使用顶级 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”并将其导出的数据作为 {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' }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?