Next.js 14构建报错:无法解析'react-server-dom-webpack/client'模块
使用Next.js 14.2.14开发项目,本地执行npm run dev运行正常,但执行npm run build构建生产版本时,触发多个Module not found: Can't resolve 'react-server-dom-webpack/client'错误,导致构建失败。错误溯源指向src/actions/action.ts、src/components/Signin.tsx等文件。
仓库地址:https://github.com/vishwas-babar/true-feeback/tree/version2
完整错误日志:
PS C:\Users\vishw\OneDrive\Desktop\next js\true_feedback> npm run build > true_feedback@0.1.0 build > next build ▲ Next.js 14.2.14 - Environments: .env Creating an optimized production build ... Failed to compile. ./node_modules/next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper.js Module not found: Can't resolve 'react-server-dom-webpack/client' https://nextjs.org/docs/messages/module-not-found Import trace for requested module: ./src/actions/action.ts ./src/components/Signin.tsx ./src/pages/SigninPage.tsx ./node_modules/next/dist/client/components/router-reducer/fetch-server-response.js Module not found: Can't resolve 'react-server-dom-webpack/client' https://nextjs.org/docs/messages/module-not-found Import trace for requested module: ./node_modules/next/dist/client/components/router-reducer/prefetch-cache-utils.js ./node_modules/next/dist/client/components/router-reducer/create-initial-router-state.js ./node_modules/next/dist/client/components/app-router.js ./node_modules/next/dist/client/app-call-server.js ./node_modules/next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper.js ./src/actions/action.ts ./src/components/Signin.tsx ./src/pages/SigninPage.tsx ./node_modules/next/dist/client/components/router-reducer/reducers/server-action-reducer.js Module not found: Can't resolve 'react-server-dom-webpack/client' https://nextjs.org/docs/messages/module-not-found Import trace for requested module: ./node_modules/next/dist/client/components/router-reducer/router-reducer.js ./node_modules/next/dist/shared/lib/router/action-queue.js ./node_modules/next/dist/client/components/use-reducer-with-devtools.js ./node_modules/next/dist/client/components/app-router.js ./node_modules/next/dist/client/app-call-server.js ./node_modules/next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper.js ./src/actions/action.ts ./src/components/Signin.tsx ./src/pages/SigninPage.tsx > Build failed because of webpack errors PS C:\Users\vishw\OneDrive\Desktop\next js\true_feedback>
按以下步骤逐一排查修复:
清理依赖缓存并重装
删除node_modules、package-lock.json文件,执行npm cache clean --force清空缓存,再运行npm install重装依赖,之后尝试构建。校验React版本兼容性
确认package.json中react、react-dom版本为18.2.0及以上(Next.js 14.x强制要求),版本不匹配则调整后重装依赖。检查Server Actions写法
确认src/actions/action.ts中的Server Actions已正确添加'use server'指令;检查Signin.tsx中调用Server Actions的方式,避免在客户端组件的渲染流程中同步执行Server Action代码(需通过表单提交或startTransition触发)。清理Next.js构建缓存
删除项目根目录下的.next文件夹,再重新执行npm run build。排查自定义Webpack配置
若项目有自定义next.config.js的webpack配置,暂时注释相关配置,验证是否是配置导致模块解析异常。升级Next.js到最新小版本
执行npm install next@latest升级到14.x系列最新版本,修复已知的构建bug。
内容的提问来源于stack exchange,提问作者vishwas babar

