如何在Vite项目中使用react-pdf?组件无法渲染问题求助
在Vite React项目中解决react-pdf组件无法渲染的问题
在Vite项目中使用react-pdf时,由于Vite的模块处理机制与传统Create React App不同,需要额外配置才能正常运行,以下是具体解决步骤:
1. 配置Vite优化依赖
在项目根目录的vite.config.ts(或vite.config.js)中添加配置,让Vite正确处理react-pdf依赖的CommonJS模块:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], optimizeDeps: { include: ['@react-pdf/renderer'] }, build: { commonjsOptions: { include: [/node_modules/] } } })
2. 为PDFViewer设置高度样式
默认情况下PDFViewer未设置高度,会导致渲染后无法看到内容,在App.css中添加样式:
.pdf-viewer { height: 80vh; border: 1px solid #ccc; }
接着在App.tsx中给PDFViewer添加类名:
<PDFViewer className="pdf-viewer"> <MyDocument /> </PDFViewer>
3. 重启开发服务
修改配置后,重启Vite开发服务器,确保配置生效。
完成以上步骤后,react-pdf的组件即可正常渲染。
内容的提问来源于stack exchange,提问作者Mats Alexander Nissen-lie
相关产品推荐
相关产品推荐

