NextJS+TypeScript项目执行yarn dev时出现TypeError: Cannot read property 'cwd' of undefined的问题求助
问题描述
我在运行yarn dev时反复遇到这个错误,开发和生产环境都会出现:
next-dev.js?53bc:89 Error was not caught TypeError: Cannot read property 'cwd' of undefined at Module.eval (parsers.js?f09d:27) at eval (parsers.js:252) at Module../node_modules/@sentry/node/esm/parsers.js (_app.js?ts=1619702971940:3455) at webpack_require (webpack.js?ts=1619702971940:873) at fn (webpack.js?ts=1619702971940:151) at eval (backend.js?5e1f:1) at Module../node_modules/@sentry/node/esm/backend.js (_app.js?ts=1619702971940:3299) at webpack_require (webpack.js?ts=1619702971940:873) at fn (webpack.js?ts=1619702971940:151) at eval (index.js?54d7:1) at Module../node_modules/@sentry/node/esm/index.js (_app.js?ts=1619702971940:3335) at webpack_require (webpack.js?ts=1619702971940:873) at fn (webpack.js?ts=1619702971940:151) at Module.eval (_app.tsx:16) at eval (_app.tsx?8548:93) at Module../src/pages/_app.tsx (_app.js?ts=1619702971940:11957) at webpack_require (webpack.js?ts=1619702971940:873) at fn (webpack.js?ts=1619702971940:151) at eval (next-client-pages-loader.js?7ae7:5) at eval (route-loader.ts?8a46:294)
我的项目基于Next.js + TypeScript,同时使用Jest和Babel。虽然网上普遍认为这是Babel兼容性问题,但我已经把所有依赖更新到最新版本了:
"@types/testing-library__jest-dom": "5.9.5", "@babel/core": "7.13.1", "@types/jest": "26.0.23", "babel-jest": "26.6.3", "jest": "26.6.3", "ts-jest": "26.5.5"
我试过了网上常见的包兼容性解决方案,但都没效果,希望能得到帮助。
解决方案
这个错误的核心原因是**@sentry/node SDK被错误地在浏览器客户端环境中加载了**——因为Next.js的_app.tsx会同时在服务端和客户端执行,而@sentry/node是专门为Node.js环境设计的,它依赖Node.js的process对象,客户端环境中没有这个对象,所以会抛出cwd(属于process的方法)未定义的错误。
你可以按照以下步骤修复:
- 区分环境加载Sentry SDK
在_app.tsx中,通过typeof window判断当前环境,只在服务端加载@sentry/node,客户端使用@sentry/browser:
// _app.tsx import type { AppProps } from 'next/app'; if (typeof window === 'undefined') { // 服务端环境加载node SDK import('@sentry/node').then(Sentry => { Sentry.init({ /* 服务端配置 */ }); }); } else { // 客户端环境加载browser SDK import('@sentry/browser').then(Sentry => { Sentry.init({ /* 客户端配置 */ }); }); } function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} />; } export default MyApp;
- 改用官方的@Sentry/nextjs集成包
官方提供了专门针对Next.js的集成包,它会自动处理服务端和客户端的环境差异,避免手动区分的麻烦:
- 安装包:
yarn add @sentry/nextjs
- 按照官方配置指引修改
next.config.js和_app.tsx,这样能彻底规避环境不匹配的问题。
检查依赖版本一致性
确保所有Sentry相关包的版本完全一致,比如@sentry/node、@sentry/browser、@sentry/nextjs必须使用相同的版本号,版本不匹配也可能导致奇怪的兼容性问题。排查Babel配置
虽然你更新了Babel依赖,但可以检查你的.babelrc或babel.config.js,确保没有禁用process的polyfill,或者没有配置导致Node.js模块被错误转译到客户端的规则。比如,确保你的Babel配置中包含next/babel预设:
{ "presets": ["next/babel"] }
如果以上方法还是不行,可以提供你的Sentry初始化代码和next.config.js内容,这样能更精准地定位问题。
内容的提问来源于stack exchange,提问作者AKFourSeven

