集成@react-pdf-viewer/core到Next.js14时生产构建失败求助
解决Next.js 14集成@react-pdf-viewer/core生产构建失败问题
问题原因
构建报错源于unist-util-visit-parents依赖版本冲突,不同第三方包(rehype-slug、remark-images)安装了该依赖的不一致版本,导致子模块导出异常;同时PDF Worker的加载配置和Webpack设置也需要适配Next.js 14的构建规则。
解决方案
1. 统一依赖版本
- 清理现有依赖文件:
rm -rf node_modules package-lock.json - 在
package.json中添加版本锁定规则(npm需额外安装强制解析工具):- 先安装
npm-force-resolutions:npm install -D npm-force-resolutions - 在
package.json中添加:"scripts": { "preinstall": "npx npm-force-resolutions" }, "resolutions": { "unist-util-visit-parents": "^5.1.3" }
- 先安装
- 重新安装依赖:
npm install
2. 修正Next.js Webpack配置
替换原next.config.js中的内容,合并重复配置并添加PDF Worker和ES模块兼容处理:
/** @type {import('next').NextConfig} */ const nextConfig = { eslint: { ignoreDuringBuilds: true, }, async rewrites() { return [ { source: "/pirsch-extended.js", destination: "https://api.pirsch.io/pirsch-extended.js", }, ]; }, webpack: (config, { isServer }) => { // 处理.node格式文件 config.module.rules.push({ test: /\.node$/, use: "raw-loader", }); // 统一PDF Worker路径,避免构建路径冲突 config.resolve.alias.set('@react-pdf-viewer/core/lib/cjs/worker', '@react-pdf-viewer/core/lib/esm/worker'); // 解决node_modules中ES模块的Webpack解析问题 config.module.rules.push({ test: /\.mjs$/, include: /node_modules/, type: 'javascript/auto', }); return config; }, }; module.exports = nextConfig;
3. 调整PDF Worker的使用方式
避免在服务器端渲染阶段加载PDF相关代码,可通过两种方式处理:
- 方式一:判断客户端环境再渲染组件
import { Viewer, Worker } from '@react-pdf-viewer/core'; import '@react-pdf-viewer/core/lib/styles/index.css'; export default function PdfViewer() { // 仅在客户端渲染PDF组件 if (typeof window === 'undefined') return null; return ( <div style={{ height: '750px' }}> <Worker workerUrl="https://unpkg.com/pdfjs-dist@3.4.120/build/pdf.worker.min.js"> <Viewer fileUrl="/your-pdf-file.pdf" /> </Worker> </div> ); } - 方式二:动态导入组件并禁用SSR
import dynamic from 'next/dynamic'; // 动态导入PDF组件,禁用服务器端渲染 const PdfViewer = dynamic(() => import('../components/PdfViewer'), { ssr: false, loading: () => <div>加载中...</div> }); export default function BlogPostPage() { return ( <div> {/* 其他页面内容 */} <PdfViewer /> </div> ); }
内容的提问来源于stack exchange,提问作者Waleed Ahmed
相关产品推荐
相关产品推荐

