Next.js项目中使用react-pdf渲染PDFViewer组件报错求助
Next.js中使用react-pdf的PDFViewer报错:PDFViewer is a web specific API
问题详情
在Next.js全客户端组件项目中,使用react-pdf 3.3.5的<PDFViewer>渲染自定义<Document>组件时,刷新页面后Node控制台抛出错误:
⨯ Internal error: Error: PDFViewer is a web specific API. You're either using this component on Node, or your bundler is not loading react-pdf from the appropriate web build.
环境:MacOS、Safari浏览器,所有组件均已添加"use client"指令。
相关代码:
Preview.tsx
"use client"; import { PDFViewer } from "@react-pdf/renderer"; import { ReactElement } from "react"; import Document from "@/components/Document/Document"; export default function Preview(): ReactElement { return ( <div className="h-full w-full"> <PDFViewer className="h-full w-full" showToolbar={false}> <Document /> </PDFViewer> </div> ); }
Document.tsx
"use client"; import React, { ReactElement } from "react"; import { Page, Text, View, Document as PDF, StyleSheet, } from "@react-pdf/renderer"; export default function Document(): ReactElement { const styles = StyleSheet.create({ page: { flexDirection: "row", backgroundColor: "#FFF", }, section: { margin: 10, padding: 10, flexGrow: 1, }, }); return ( <PDF> <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> </PDF> ); }
解决方案
1. 强制webpack加载react-pdf的web构建版本
在next.config.js中配置webpack别名,指定react-pdf使用浏览器端入口文件:
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.resolve.alias['@react-pdf/renderer'] = '@react-pdf/renderer/dist/react-pdf.browser.js'; return config; }, }; module.exports = nextConfig;
2. 动态导入PDFViewer并禁用SSR
通过lazy和Suspense动态导入组件,同时强制组件仅在客户端加载:
修改Preview.tsx:
"use client"; import { ReactElement, lazy, Suspense } from "react"; import Document from "@/components/Document/Document"; const PDFViewer = lazy(() => import("@react-pdf/renderer").then((mod) => ({ default: mod.PDFViewer })) ); export default function Preview(): ReactElement { return ( <div className="h-full w-full"> <Suspense fallback={<div>加载PDF中...</div>}> <PDFViewer className="h-full w-full" showToolbar={false}> <Document /> </PDFViewer> </Suspense> </div> ); }
3. 升级react-pdf版本
较新版本的react-pdf已优化Next.js环境兼容性,尝试升级到最新稳定版:
npm install @react-pdf/renderer@latest # 或使用yarn yarn add @react-pdf/renderer@latest
原因说明
错误本质是Next.js的bundler误加载了react-pdf的Node.js环境构建包,而<PDFViewer>是浏览器专属组件,无法在Node环境运行。上述方案通过指定web构建入口、强制客户端加载或升级组件版本,解决环境不匹配问题。
内容的提问来源于stack exchange,提问作者Gökhan Gündüz
相关产品推荐
相关产品推荐

