Home  >  Q&A  >  body text

Create an error in Vue.js for a component that doesn't exist.

<p>When we try to use a component that doesn't exist, I want an error to be generated instead of a simple warning in the console: </p> <pre class="brush:php;toolbar:false;">[Vue warn]: Failed to resolve component: nonexisting-component If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. at <MainLayout onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > at <RouterView> at <App></pre> <p>Sometimes people break the flow, but they may not notice because the component doesn't show up at all. Is there any way to solve this problem? </p>
P粉765570115P粉765570115465 days ago578

reply all(1)I'll reply

  • P粉245489391

    P粉2454893912023-08-04 15:58:54

    It is very easy to solve this problem using the Rollup plugin. Plug-ins can be written directly in vite.config.js. Here you can use rollup's resolveId hook. Vite/Rollup calls this hook when it cannot resolve an import. If it's a Vue Single File Component (SFC) you can resolve it to any placeholder component of your choice:

    import { fileURLToPath, URL } from 'node:url'
    
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    
    // https://vitejs.dev/config/
    export default defineConfig({
        plugins: [
            vue(),
            {
                resolveId(id) {
                    if (id.endsWith('.vue')) {
                        // issue the error into the terminal
                        console.error(`Component "${id}" is missing!`);
                        return './src/components/Placeholder.vue';
                    }
                },
            }
        ],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url))
            }
        }
    })

    Translate src/components/Placeholder.vue (if you want it to be empty, just do this):

    <script setup>
        console.error('Some component is missing, check the build terminal!');
    </script>
    <template>
        <div class="background:orange;color:red">Some component is missing, check the build terminal!</div>
    </template>

    reply
    0
  • Cancelreply