DEV Community

Mert
Mert

Posted on

How to Handle Dynamic Import Errors in Vuejs

Nowadays, one of the most challenging parts of frontend development is error handling. Sometimes we don't want to think about the worst cases or we just don't have time to handle them because of deadlines but it doesn't mean they aren't important.

Today, I'm going to talk about dynamic import error handling. Although this topic is about Vuejs, you can see this as a generic solution for other view libraries.

As our application grows, we may want to reduce JavaScript bundle size in order to decrease initial load time and performance. There are couple of techniques to achieve this goal like reducing image sizes, lazy loading and code splitting.

Code splitting is a technique which allows you to split your JavaScript bundles into different parts which can be loaded at anytime in the future. We can split route codes with JavaScript's import() method but due to nature of it, it returns a promise after completion or failure of an asynchronous operation.

How

In Vuejs, we can set import methods return value to component key of route object like below. With this way JavaScript bundle of About page will be only called if user navigate to it.

Not handling error

With this code above, we only handle the success scenario. If we want to handle failure case, we can create a generic component which isn't imported dynamically and then return it on catch like below.

Handling error

This generic DynamicImportError component will be loaded on initial request. What if our initial request fails? Well... I think that is different problem.

Conclusion

You can say that DynamicImportError will increase initial bundle size, but it is a dummy component and it only informs visitors that something went wrong so it won't have a big size. In my opinion it has a pretty low opportunity cost.

Top comments (0)