如何使用异步 ESM 导入获取 ESM 模块

How do I get a ESM module using the Async ESM import

我在 plunker 中有以下代码...

// Thing.js
export class Thing{
  constructor(){
    console.log("This thing is alive!!!!");
  }
}
// index
import("./Thing.js").then(
  (Thing)=>{
      new Thing();
  }
)

但我得到的是

VM662 script.js:5 Uncaught (in promise) TypeError: Thing is not a constructor

?

您的问题是您试图将 Thing 当作默认导出而不是命名导出来读取。这些都可以工作:

// Thing.js
export class Thing{
  constructor(){
    console.log("This thing is alive!!!!");
  }
}
// index
import("./Thing.js").then(
  ({Thing})=>{ // NOTE destructuring since Thing is a named export
      new Thing();
  }
)

或这个

// Thing.js
export default class Thing{ // NOTE default
  constructor(){
    console.log("This thing is alive!!!!");
  }
}
// index
import("./Thing.js").then(
  (Thing)=>{ // No destructuring needed, can read Thing directly
      new Thing();
  }
)