【问题标题】: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();
}
)