简体   繁体   中英

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

I have the following code in a plunker...

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

But what I get is

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

?

Your problem is that you're trying to read Thing as if it were a default export rather than a named export. Either of these will work:

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

or this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM