DEV Community

Mert
Mert

Posted on

4 1

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.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay