Next.js(TypeScript)中document未定义及预渲染、构建权限问题排查
问题1:预渲染时出现 ReferenceError: document is not defined
多个页面(/about_us、/cart/check_out、/cart、/contact、/shop/products)预渲染失败,报错栈如下:
ReferenceError: document is not defined
at m (/vercel/path0/.next/server/app/(routes)/about_us/page.js:1:4079)
at nM (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:47419)
at nL (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:64674)
at nI (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:46806)
at nM (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:47570)
at nM (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:61663)
at nL (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:64674)
at nB (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:67657)
at nF (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:66824)
at nL (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:64990)
Error occurred prerendering page "/about_us".
原因与解决方法
- 核心原因:Next.js 服务端预渲染阶段不存在浏览器环境的
document对象,代码中直接调用了该对象导致报错。 - 修复方案:
- 将依赖
document的代码移至客户端执行逻辑:
使用 React 的useEffect钩子(仅在客户端渲染时触发):import { useEffect } from 'react'; useEffect(() => { // 此处编写需要操作 document 的代码 const targetElement = document.getElementById('target-id'); if (targetElement) { // 执行 DOM 操作或初始化依赖浏览器的逻辑 } }, []); - 对依赖浏览器环境的第三方组件/库使用动态导入并禁用服务端渲染:
import dynamic from 'next/dynamic'; const ClientOnlyComponent = dynamic( () => import('../components/YourComponent'), { ssr: false } ); - 排查全局导入的脚本,确保依赖
document的代码仅在客户端加载。
- 将依赖
问题2:本地构建时触发权限错误 errno: -4048, code: 'EPERM', syscall: 'open'
项目在 localhost 运行正常,但执行构建命令时出现权限报错。
原因与解决方法
- 核心原因:Windows 环境下,构建进程对项目目录或
.next文件夹无读写权限,或文件被其他进程(编辑器、杀毒软件)锁定。 - 修复方案:
- 以管理员身份打开终端,重新执行构建:
npm run build - 关闭占用项目文件的程序:关闭 VS Code 等编辑器,暂停杀毒软件实时防护后重试构建。
- 清理缓存文件后重新构建:
rmdir /s .next rmdir /s node_modules/.cache npm install npm run build - 检查项目文件夹权限:右键项目文件夹 → 属性 → 安全,确保当前用户拥有「完全控制」权限。
- 以管理员身份打开终端,重新执行构建:
内容的提问来源于stack exchange,提问作者Hossam Ahmed

