You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:31:09