在Vue.js中创建一个用于不存在组件的错误。
P粉765570115
P粉765570115 2023-08-03 17:43:26
[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 &lt;MainLayout onVnodeUnmounted=fn&lt;onVnodeUnmounted&gt; ref=Ref&lt; undefined &gt; &gt; at &lt;RouterView&gt; at &lt;App&gt;</pre> <p>有时候人们会破坏流程,但他们可能没有注意到,因为组件根本不会显示出来。有没有办法解决这个问题?</p>
P粉765570115
P粉765570115

全部回复(1)
P粉245489391

使用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>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号