Pal*_*pad 6 node.js es6-modules
Node.js 文档的加密模块文档使用顶级await导入,但它显然不是动态导入
下面的两条语句有什么区别(它们似乎做了相同的事情)
import * as fs from 'fs'
const fs_ = await import('fs'); // why use this?
Run Code Online (Sandbox Code Playgroud)
[不重复]
import()静态导入 EC 模块(而不是import()动态导入),它与 CommonJS 模块require()语法非常相似,这是顶级 wait 关键字的唯一目的支持者:(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 -----' );
Run Code Online (Sandbox Code Playgroud)
{ default: 'data from module-1' }
{ default: 'data from module-1' }
----- MAIN MODULE END -----
{ default: 'data from module-2' }
{ default: 'data from module-2' }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3934 次 |
| 最近记录: |