Home > OS >  How to use await import() for an exported constructor function?
How to use await import() for an exported constructor function?

Time:08-24

I have this as my function constructor:

test.js

const myConstructor = function(){
  this.hi = 'hi'
  console.log(this.hi)
}
export default myConstructor

And I'm trying to await import() it in test2.js:

test2.js

const test = await import('./test.js')

new test()

This fails with TypeError: test is not a constructor.

However, if I import it normally it works fine:

test2.js

import test from './test.js'
//const test = await import('./test.js')

new test()

^^ prints hi to the console.

What is going on here? Why do the two approaches behave so differently for constructor functions? This doesn't appear to happen for normal functions.

I've had to work around this by calling the constructor function directly within the constructor function module, and this is not ideal.

CodePudding user response:

Dynamic import returns:

It returns a promise which fulfills to an object containing all exports from moduleName, with the same shape as a namespace import (import * as name from moduleName): an object with null prototype, and the default export available as a key named default.

If its Promise only resolved to the default export, you wouldn't be able to use any named exports it may have. So, you need:

const testNamespace = await import('./test.js')

new testNamespace.default()

CodePudding user response:

Async import returns module, so you need to use .default property to access default export of module.

const test = await import('./test.js').default

new test()
  • Related