vue.jsnuxt.jsvite

Load fallback component if main component does not exits


The MainFooter might not exist in the themes folder, in that case we are loading fallback component.

Here is what I came up with:

<template>
    <component :is="footerComponent" />
</template>

<script lang="ts" setup>
    const footerComponent = computed(() => {
        try {
            return import("@wtp/MainFooter.vue");
        } catch (error) {
            console.error(error);
            return defineAsyncComponent(() => import("./FallbackFooter.vue"));
        }
    });
</script>

This works but gives the following error on frontend:

[plugin:vite:import-analysis] Failed to resolve import "@wtp/MainFooter.vue" from "components/MainFooter.vue". Does the file exist?

Any better ways to do this?


Solution

  • Managed to solve the issue, by using import.meta.glob to check if the component exists.

    <template>
        <component :is="footerComponent" />
    </template>
    
    <script lang="ts" setup>
        const modules = import.meta.glob("@wtp/MainFooter.vue");
        const footerComponent = shallowRef();
    
        if (modules["@wtp/MainFooter.vue"]) {
            // @ts-ignore
            footerComponent.value = defineAsyncComponent(() => modules["@wtp/MainFooter.vue"]());
        } else {
            footerComponent.value = defineAsyncComponent(() => import("./FallbackFooter.vue"));
        }
    </script>