Next.js项目因Babel报错构建失败,求解决方案
修复Next.js构建错误:TSSatisfiesExpression无效节点类型
错误信息
./pages/_app.tsx Error: [BABEL] C:\Projects\skribeNew\app-web\pages\_app.tsx: You gave us a visitor for the node type TSSatisfiesExpression but it's not a valid type at verify (C:\Projects\skribeNew\app-web\node_modules\next\dist\compiled\babel\bundle.js:1910:397612) at Function.explode (C:\Projects\skribeNew\app-web\node_modules\next\dist\compiled\babel\bundle.js:1910:396515) at C:\Projects\skribeNew\app-web\node_modules\next\dist\compiled\babel\bundle.js:1:49254 at Generator.next (<anonymous>) at Function.<anonymous> (C:\Projects\skribeNew\app-web\node_modules\next\dist\compiled\babel\bundle.js:1:79767) at Generator.next (<anonymous>) at evaluateSync (C:\Projects\skribeNew\app-web\node_modules\next\dist\compiled\babel\bundle.js:1910:717268) at Function.sync (C:\Projects\skribeNew\app-web\node_modules\next\dist\compiled\babel\bundle.js:1910:715284) at sync (C:\Projects\skribeNew\app-web\node_modules\next\dist\compiled\babel\bundle.js:1:80263) at sync (C:\Projects\skribeNew\app-web\node_modules\next\dist\compiled\babel\bundle.js:1910:716601)
修复方案
升级Babel依赖到兼容版本
TSSatisfiesExpression是Babel 7.21.0及以上版本支持的节点类型,执行以下命令更新核心依赖:# npm npm update @babel/core @babel/preset-typescript @babel/plugin-syntax-typescript # yarn yarn upgrade @babel/core @babel/preset-typescript @babel/plugin-syntax-typescript # pnpm pnpm update @babel/core @babel/preset-typescript @babel/plugin-syntax-typescript解决Next.js内置Babel的版本冲突
Next.js自带编译好的Babel包,可能和项目手动安装的依赖版本不兼容。通过锁定依赖版本解决:- 在
package.json中添加resolutions字段:"resolutions": { "@babel/core": "^7.21.0", "@babel/preset-typescript": "^7.21.0" } - 重新安装依赖:
# yarn直接执行 yarn install # npm需要先安装npm-force-resolutions工具 npm install -g npm-force-resolutions npm install --force-resolutions
- 在
升级TypeScript到支持satisfies的版本
satisfies操作符是TypeScript 4.9.0引入的,确保项目TS版本达标:- 执行升级命令:
npm update typescript - 检查
tsconfig.json的compilerOptions,确保配置正确:"compilerOptions": { "target": "ESNext", "module": "ESNext", "skipLibCheck": true }
- 执行升级命令:
清理缓存后重新构建
旧缓存可能导致版本冲突残留,执行以下步骤:# 删除Next.js构建缓存和node_modules缓存 # Windows rd /s /q .next node_modules\.cache # macOS/Linux rm -rf .next node_modules/.cache # 重新安装依赖并构建 npm install npm run build检查自定义Babel配置
如果项目有.babelrc或babel.config.json,确保配置兼容:{ "presets": [ "next/babel", ["@babel/preset-typescript", { "allowDeclareFields": true }] ] }避免同时使用过时的TypeScript相关插件,以
@babel/preset-typescript为主。
内容的提问来源于stack exchange,提问作者Md. Nizam Uddin Mahmud
相关产品推荐
相关产品推荐

