【问题标题】:How do I get a ESM module using the Async ESM import如何使用异步 ESM 导入获取 ESM 模块
【发布时间】:2019-06-19 01:47:22
【问题描述】:

我在 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

?

【问题讨论】:

    标签: javascript object ecmascript-6 es6-module-loader


    【解决方案1】:

    您的问题是您尝试将 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();
      }
    )
    

    【讨论】:

    猜你喜欢
    • 2021-01-16
    • 2021-11-23
    • 2022-01-20
    • 2020-08-13
    • 2023-01-31
    • 2020-12-23
    • 2019-10-24
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多