Vite React项目执行npm run preview后页面空白且报错TypeError: e is null
Vite React项目build/preview后页面空白,控制台报
TypeError: e is null 问题场景
使用Vite初始化React项目后,执行npm run build构建生产包,再运行npm run preview预览时,页面完全空白,浏览器控制台抛出以下错误:
TypeError: e is null
Uncaught TypeError: e is null
项目配置文件
vite.config.js
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], })
package.json
{ "name": "vite-react-app", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "@vitejs/plugin-react": "^4.2.1", "vite": "^5.0.8" } }
问题解决
该问题并非Vite配置导致,而是项目中存在开发环境未暴露的组件错误,需重点排查以下几点:
- 组件文件名与默认导出的函数名不匹配(比如文件名是
Header.jsx,但导出的是export default Navbar) - 同一组件文件被用不同名称重复导入(比如一处用
import Header from './Header',另一处用import Navbar from './Header') - 组件中存在依赖开发环境的DOM操作(比如获取某个仅在dev模式下存在的元素,生产环境中该元素被移除导致
null) - 未处理的
null/undefined值渲染(比如直接访问props.data.name但props.data为null)
逐一排查并修复这些组件错误后,重新执行npm run build和npm run preview即可正常显示页面。
内容的提问来源于stack exchange,提问作者Yash Patil
相关产品推荐
相关产品推荐

