首页  >  问答  >  正文

在Vue.js中创建一个用于不存在组件的错误。

<p>当我们尝试使用一个不存在的组件时,我希望生成一个错误,而不是像控制台中的简单警告那样:</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>有时候人们会破坏流程,但他们可能没有注意到,因为组件根本不会显示出来。有没有办法解决这个问题?</p>
P粉765570115P粉765570115442 天前553

全部回复(1)我来回复

  • P粉245489391

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

    使用Rollup插件解决这个问题非常容易。插件可以直接编写在vite.config.js中。在这里,您可以使用rollup的resolveId钩子。当Vite/Rollup无法解析导入时,它会调用此钩子。如果是Vue单文件组件(SFC),您可以将其解析为任何选择的占位符组件:

    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))
            }
        }
    })

    翻译src/components/Placeholder.vue(如果您希望它为空,只需这样做):

    <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>

    回复
    0
  • 取消回复