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?