Next.js构建报错:npm run build失败但dev正常,预渲染出错
在使用Next.js开发大型项目时,npm run dev运行完全正常,但执行npm run build时触发构建错误,问题集中在动态路由页面的预渲染环节。
报错信息
> > Build error occurred Error: Export encountered errors on following paths: /categories/[id]: /categories/21 /categories/[id]: /categories/22 /categories/[id]: /categories/32 /categories/[id]: /categories/33 /categories/[id]: /categories/34 /categories/[id]: /categories/35 /categories/[id]: /categories/36 /categories/[id]: /categories/37 /categories/[id]: /categories/38 /categories/[id]: /categories/39 /categories/[id]: /categories/40 /footerPages/[pageId]: /footerPages/3 /footerPages/[pageId]: /footerPages/4 /footerPages/[pageId]: /footerPages/7 /gallery/[galleryid]: /gallery/10 /gallery/[galleryid]: /gallery/7 /gallery/[galleryid]: /gallery/8 /gallery/[galleryid]: /gallery/9 /profile/[profileId]: /profile/14 /profile/[profileId]: /profile/15 /profile/[profileId]: /profile/4
错误原因
reason: Unexpected token < in JSON at position 0
问题分析
这个错误是典型的JSON解析失败——代码尝试解析的内容不是合法JSON,而是以<开头的HTML(通常是404页面、服务器错误页面或其他非JSON响应)。dev模式下页面按需渲染,不会一次性预渲染所有动态路由;但build时Next.js会批量预渲染所有页面,此时如果某个动态路由的数据请求返回HTML而非JSON,就会触发整个构建失败。
解决步骤
检查动态路由的数据获取逻辑
重点核对getStaticProps或getServerSideProps中的API请求代码,确认构建环境下的API地址是否正确(比如dev用本地API,build用生产API,但生产API可能未部署或路径写错)。验证API响应合法性
手动访问报错路径对应的API接口(比如/api/categories/21),查看返回内容是否为合法JSON。如果返回HTML(404/500页面等),说明后端接口存在问题,需要先修复服务或接口路径。添加错误捕获逻辑
在数据获取函数中增加错误处理,避免单个请求失败导致整个构建终止。示例代码:export async function getStaticProps({ params }) { try { const res = await fetch(`https://your-api-url/categories/${params.id}`); if (!res.ok) { throw new Error(`API请求失败: ${res.status}`); } const data = await res.json(); return { props: { data } }; } catch (error) { console.error('获取分类数据失败:', error); // 返回默认数据或标记错误状态,保证构建继续 return { props: { data: null } }; } }核对
getStaticPaths配置
如果使用静态生成,检查getStaticPaths返回的paths数组中的参数是否有效——比如某些ID在后端已被删除,但paths仍包含这些无效ID,导致请求返回错误。确认环境变量正确性
检查构建时使用的环境变量是否正确,比如API地址是否通过环境变量注入,确保构建环境下的变量指向可用的后端服务。
内容的提问来源于stack exchange,提问作者Romanch haque

