Vite 本身不提供运行时错误弹窗,需在应用层用 window.onerror 和 unhandledrejection 事件捕获错误,并通过原生 DOM 或框架方案(Vue/React)实现自定义弹窗提示,注意区分开发红屏与运行时错误。

在 Vite 项目中,Vite 本身不提供运行时错误弹窗功能(它只负责开发服务器和构建),但你可以结合前端框架(如 Vue、React)或纯 JavaScript,在 应用层捕获错误并显示自定义弹窗。关键在于区分两类错误:开发阶段的 Vite 报错(终端/浏览器控制台)和运行时 JS 错误(需手动监听处理)。
捕获全局 JavaScript 运行时错误
使用 window.onerror 和 window.addEventListener('error') 捕获未处理的脚本错误、资源加载失败等:
-
window.onerror可获取错误消息、文件名、行号、列号和错误对象 -
unhandledrejection事件用于捕获 Promise 拒绝且未被.catch()处理的情况 - 注意:部分跨域脚本错误会受限(显示为
Script error.),可通过<script crossorigin>和服务端配置 CORS 解决
封装一个轻量弹窗组件(纯 JS 示例)
无需依赖 UI 库,用原生 DOM 实现一个可复用的错误提示弹窗:
详细的 Three.js 3D 图形参考,涵盖场景设置、相机、几何体、材质、光照、动画、控制器、加载器、数学工具和调试。
function showErrorDialog(message, details = '') {
// 避免重复创建
if (document.getElementById('error-dialog')) return;
const dialog = document.createElement('div');
dialog.id = 'error-dialog';
dialog.style.cssText = `
position: fixed; top: 20px; right: 20px; max-width: 400px;
background: #fff; border: 1px solid #e0e0e0; border-radius: 6px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 9999;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
`;
dialog.innerHTML = `
<div style="padding: 16px;">
<div style="font-weight: 600; color: #d32f2f; margin-bottom: 8px;">⚠️ 运行出错</div>
<div style="font-size: 14px; color: #333; white-space: pre-wrap;">${message}</div>
${details ? `<pre class="brush:php;toolbar:false;" style="margin-top: 12px; padding: 8px; background: #f5f5f5; border-radius: 4px; font-size: 12px; overflow-x: auto;">${details}` : ''}
`;
document.body.appendChild(dialog);
}
// 使用示例(可放在 main.js 或入口逻辑中)
window.onerror = (msg, url, line, col, error) => {
const details = error ? `${error.stack || ''}` : '';
showErrorDialog(`JS 错误:${msg}`, `文件:${url} | 行:${line} 列:${col}\n\n${details}`);
};
window.addEventListener('unhandledrejection', e => {
const reason = e.reason instanceof Error ? e.reason.stack : String(e.reason);
showErrorDialog('异步错误:Promise 被拒绝', `原因:${reason}`);
});
在 Vue / React 中更优雅地集成
推荐将错误提示抽象为可组合函数或 Hook,配合状态管理统一控制显示逻辑:
立即学习“Java免费学习笔记(深入)”;
-
Vue 3(组合式 API):用
ref控制弹窗显隐,provide/inject或 Pinia 全局分发错误 -
React:封装
useErrorDialog()Hook,内部用useState+useEffect监听全局错误事件 - 避免在组件挂载时重复绑定事件,建议在根组件
mounted/useEffect(() => {...}, [])中一次性注册
注意事项与调试建议
Vite 开发时看到的红屏(如模块解析失败、语法错误)是 Vite Dev Server 的 HMR 错误界面,无法用 JS 拦截或覆盖 —— 它发生在代码执行前。你只能优化运行时体验:
- 确保错误弹窗样式不被 CSS 重置或框架样式干扰(加
!important或内联 style) - 生产环境建议关闭详细堆栈(仅提示友好信息),避免泄露敏感路径或逻辑
- 可配合 Sentry、LogRocket 等工具上报错误,弹窗作为用户侧即时反馈

















