Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

317
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!