Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
How to use await import() for an exported constructor function?

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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()
about 4 years ago · Juan Pablo Isaza Relatório

0

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()
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda