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

Vite+React集成@react-pdf/renderer v3出现TypeError报错求助

问题:Vite+React TS环境下使用@react-pdf/renderer报错Uncaught TypeError: Cannot read properties of undefined (reading 'call')

报错信息

Uncaught TypeError: Cannot read properties of undefined (reading 'call')

复现步骤

  • 使用Vite创建React TS项目:
    npm init vite@latest vite-project --template react-ts
    
  • 创建示例PDF文档组件(如src/MyDocument.tsx):
    import React from 'react';
    import pdf from '@react-pdf/renderer';
    const { Page, Text, View, Document, StyleSheet } = pdf;
    
    // 创建样式
    const styles = StyleSheet.create({
      page: {
        flexDirection: 'row',
        backgroundColor: '#E4E4E4',
      },
      section: {
        margin: 10,
        padding: 10,
        flexGrow: 1,
      },
    });
    
    // 文档组件
    export const MyDocument = () => (
      <Document>
        <Page size='A4' style={styles.page}>
          <View style={styles.section}>
            <Text>Section #1</Text>
          </View>
          <View style={styles.section}>
            <Text>Section #2</Text>
          </View>
        </Page>
      </Document>
    );
    
  • 替换src/App.tsx内容:
    import React from 'react';
    import { PDFViewer } from '@react-pdf/renderer';
    import { MyDocument } from './MyDocument';
    
    const App = () => (
      <PDFViewer>
        <MyDocument />
      </PDFViewer>
    );
    
    export default App;
    
  • 启动开发服务器,查看控制台报错

注:该场景在Create React App中可正常运行,但Vite环境下触发报错。

解决方案

1. 修复组件导入缺失

确保App.tsx中正确导入MyDocument组件,缺失导入会导致组件未定义,可能间接引发后续报错。

2. 配置Vite兼容CommonJS模块

@react-pdf/renderer及其依赖多为CommonJS格式,Vite默认优先处理ESM模块,导致解析异常。修改vite.config.ts添加以下配置:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  // 预优化指定依赖
  optimizeDeps: {
    include: ['@react-pdf/renderer', '@react-pdf/fonts', '@react-pdf/layout'],
  },
  // 构建时兼容CommonJS模块
  build: {
    commonjsOptions: {
      include: [/node_modules/],
    },
  },
})

3. (可选)降级依赖版本

若上述配置无效,可尝试降级到@react-pdf/renderer@2.2.0,该版本与Vite兼容性更稳定:

npm install @react-pdf/renderer@2.2.0

内容的提问来源于stack exchange,提问作者QuaCode

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:30:51