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

336
Visualizações
Dynamic imports - Unable to catch error due to compile error

I have a module that may or may not use another external validator module. If the validator is not installed in the project I don't want to proceed with the import and catch the error and advice that the validator module doesn't exist.

I managed to handle this successfully using a try catch with require():

if (messages) {
      try {
        Validator = require("@test/validator").default;
        console.log(Validator);
      }
      catch (e) {
        if (e.code === "MODULE_NOT_FOUND") {
            console.error("Can't load dvalidator!");
        } else {
          throw e;
        }
      }
}

Although this works as expected, I don't feel like this is the way to go and instead I would like to use the popularly suggested feature import().

When I try to use the dynamic import, I get a compile error stating This dependency was not found:

I'm trying to use the dynamic import as follows:

if (messages) {
      import('@test/validator')
      .then(Validator => {
        console.log(Validator)
      })
      .catch(err => console.error(err));
}

I'm not sure if I'm misunderstanding the concept of import(), but I expect the import not to take place if the module doesn't exists and catch the error at my own preference. Instead, it is still trying to import it which why I get the compile error.

Is there any way I can achieve this using dynamic imports or should I stick to my first example using try catch?

about 4 years ago · Juan Pablo Isaza
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