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