Search code examples
javascriptobjectecmascript-6es6-module-loader

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

?


Solution

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