You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js执行yarn build时_document.js出现两处报错,求解决方法

问题1:next/document should not be imported outside of pages/_document.js 报错解决
  • 全局搜索所有文件中的from 'next/document'导入语句,确认仅在pages/_document.js文件中存在该导入。重点排查其他页面/公共组件是否误用了next/document导出的Head组件,普通页面的头部组件需要从next/head导入,不能使用next/document中的Head。
  • 检查_document.js的路径与命名:必须存放在项目根目录的pages文件夹下,文件名为全小写的_document.js,不可放在pages的子目录中,也不可出现大小写拼写偏差(如_Document.js、_document.JS都会触发规则校验失败)。
  • 若确认所有导入逻辑符合规范仍报错,可通过ESLint规则覆盖关闭该校验,在项目根目录的.eslintrc.json中添加如下配置:
{
  "rules": {
    "@next/next/no-document-import-in-page": "off"
  }
}

如需临时跳过ESLint校验验证打包逻辑,可执行命令yarn run build --no-lint。

问题2:Component definition is missing display name 报错解决

该报错由getInitialProps中传入renderPage的匿名函数组件触发,ESLint的react/display-name规则要求所有组件需要配置显示名称,两种修复方案可选:

  1. 给匿名组件添加displayName,修改renderPage相关代码如下:
const page = renderPage((App) => {
  const CollectStyles = (props) => sheet.collectStyles(<App {...props} />)
  CollectStyles.displayName = 'CollectStyles'
  return CollectStyles
})
  1. 直接关闭该ESLint校验规则,在.eslintrc.json的rules配置中添加:
"react/display-name": "off"

升级NextJS canary版本无效的原因是以上两个均为ESLint规则校验报错,不属于NextJS核心运行时Bug,升级版本无法解决规则校验问题。


内容的提问来源于stack exchange,提问作者Marin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:06:05