Next.js+React+TS环境下PDF编译失败,求解决方案
问题描述
我正在基于Tim Baker的模板开发作品集应用,完全没有TypeScript经验,刚接触Node开发。我的目标是在浏览器中打开data.tsx里定义路径的PDF文件,但遇到了如下编译错误:
Build Error Failed to compile Next.js (14.2.3) ./src/assets/resume.pdf Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders (Source code omitted for this binary file) Import trace for requested module: ./src/assets/resume.pdf ./src/data/data.tsx ./src/pages/index.tsx
相关代码片段
data.tsx
// data.tsx import resumePDF from '../assets/resume.pdf'; import porfolioImage1 from '../images/portfolio/portfolio-1.jpg'; ... /** * Hero section */ export const heroData: Hero = { imageSrc: heroImage, name: `I'm freshflayedwaffle`, actions: [ { href: resumePDF, text: 'Resume', primary: true, Icon: ArrowDownTrayIcon, } ], }; ... /** * Portfolio section */ export const portfolioItems: PortfolioItem[] = [ { title: 'Project title 1', description: 'Give a short description of your project here.', url: 'https://reactresume.com', image: porfolioImage1, },
hero.tsx
// partial hero component - hero.tsx <div className="flex w-full justify-center gap-x-4"> {actions.map(({href, text, primary, Icon}) => ( <a className={classNames( 'flex gap-x-2 rounded-full border-2 bg-none px-4 py-2 text-sm font-medium text-white ring-offset-gray-700/80 hover:bg-gray-700/80 focus:outline-none focus:ring-2 focus:ring-offset-2 sm:text-base', primary ? 'border-orange-500 ring-orange-500' : 'border-white ring-white', )} href={href} key={text}> {text} {Icon && <Icon className="h-5 w-5 text-white sm:h-6 sm:w-6" />} </a> ))} </div>
dataDef.ts
// dataDef.ts interface HeroActionItem { href: string; text: string; primary?: boolean; Icon?: ForwardRefExoticComponent<Omit<SVGProps<SVGSVGElement>, 'ref'>>; }
types.d.ts
// types.d.ts declare module '*.jpg' { const value: string; export default value; } declare module '*.pdf' { const value: string; export default value; }
已尝试方案
模仿图片的导入配置处理PDF,出现上述错误;查找webpack loader但未找到适配PDF的;发现react-pdf库,但觉得这两种方案过度设计,可能忽略了简单问题,多次搜索仍无头绪。
解决方案
用Next.js自带的静态资源处理能力就能解决,不需要额外依赖或配置:
- 把
resume.pdf移动到项目根目录的public文件夹下(没有的话直接创建),路径为public/resume.pdf - 删除
data.tsx里的import resumePDF from '../assets/resume.pdf';语句 - 修改
heroData中的PDF路径为直接引用public下的资源:actions: [ { href: '/resume.pdf', text: 'Resume', primary: true, Icon: ArrowDownTrayIcon, } ],
Next.js会自动将public文件夹下的资源作为静态资源对外服务,访问路径就是文件名(或子文件夹路径),完全避开webpack编译的loader问题,直接满足在浏览器中打开PDF的需求。
内容的提问来源于stack exchange,提问作者freshflayedwaffle
相关产品推荐
相关产品推荐

