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

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

我在 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();
  }
)

关于javascript - 如何使用异步 ESM 导入获取 ESM 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56659026/

相关文章:

javascript - 如何对 JQuery Handlebar 生成的数据进行排序?

javascript - 将自定义标题和消息添加到 Facebook 对话框共享

javascript - 递归地从嵌套数组中删除对象

javascript - javascript setter/getter 的使用

javascript - 如果映射项为 null 或为空,则通过连接 2 个其他属性使用替代值

javascript - react BaseTable rowSpan "flickering"

javascript - HTML5 中防止 GPS 欺骗的方法?

java - 从存储对象作为值的 HashMap 中获取最小值

c++ - CUDA 和复制构造函数

javascript - 编译 Typescript 而不丢失 node_modules 路径?