Next.js导入PDF失败,模块解析错误寻求解决方案
Next.js中react-pdf+react-pageflip实现PDF翻书的模块解析错误解决方法
错误原因
Next.js默认的webpack配置未包含处理PDF文件的规则,直接通过import导入PDF文件会触发模块解析失败。
解决方法
方法一:直接使用public目录下的PDF路径(推荐)
由于PDF文件放在public目录中,无需通过import导入,直接使用绝对路径即可:
- 删除代码中
import pdfFile from "../public/Issue.pdf"这一行 - 将
Document组件的file属性改为"/Issue.pdf"
修改后的关键代码片段:
import React, { useState } from 'react'; import HTMLFlipBook from "react-pageflip"; import { pdfjs, Document, Page as ReactPdfPage } from "react-pdf"; pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; // ... 其他代码保持不变 <Document file="/Issue.pdf" onLoadSuccess={onDocumentLoadSuccess} onLoadError={onError}> {Array.from(new Array(numPages), (el, index) => ( <div key={index}> <ReactPdfPage pageNumber={index + 1} width={400} /> </div> ))} </Document>
方法二:配置webpack支持PDF文件导入
如果必须通过import导入PDF,需修改Next.js的webpack配置:
针对Next.js Pages Router
- 安装
file-loader:
npm install file-loader --save-dev
- 在项目根目录创建或修改
next.config.js:
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.module.rules.push({ test: /\.pdf$/, use: { loader: 'file-loader', options: { name: '[name].[ext]', outputPath: 'static/pdf/', publicPath: '/_next/static/pdf/' } } }); return config; } } module.exports = nextConfig;
针对Next.js 13+ App Router(webpack5内置支持)
直接修改next.config.js:
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.module.rules.push({ test: /\.pdf$/, type: 'asset/resource', generator: { filename: 'static/pdf/[name].[hash][ext]' } }); return config; } } module.exports = nextConfig;
额外注意事项
代码中导入的Page组件被重命名为ReactPdfPage,但使用时写的是<Page>,这会导致组件找不到的错误,需将使用处改为<ReactPdfPage>。
内容的提问来源于stack exchange,提问作者franzyk
相关产品推荐
相关产品推荐

