服务器构建Next13项目遇语法错误:Node.js升级后仍报??运算符错误
问题:Next.js 13构建时出现空值合并运算符语法错误,高版本Node.js无效仅v14可用
错误信息
执行构建命令npm run build:stag_gg时抛出语法错误:
> TTMall_Next@1.0.0 build:stag_gg > cross-env MODE=staging_gg next build /mnt/www/ttmall_front_next/node_modules/next/dist/build/index.js:347 ...pageKeys.app ?? [], ^ SyntaxError: Unexpected token '?' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.<anonymous> (/mnt/www/ttmall_front_next/node_modules/next/dist/cli/next-build.js:10:37) at Module._compile (internal/modules/cjs/loader.js:999:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) [PM2] Applying action deleteProcessId on app [ttmall_front_next](ids: [ 0 ]) [PM2] [ttmall_front_next](0) ✓
已完成的排查
- 兼容性验证:空值合并运算符是ES2020特性,Node.js v14及以上版本原生支持,v16.13.2、v19.0.0理论上都应兼容。
- 版本确认:通过nvm切换到v16.13.2(npm v8.1.2)、升级到v19.0.0,
node -v均显示对应版本,但构建错误未解决。 - package.json指定版本:在package.json中声明Node.js v16.13.2,无效。
- 低版本测试:切换到Node.js v14.10.0时,项目可正常构建。
操作日志片段:
+ node -v v16.13.2 SSH: Failed to get hostname [XXX: XXX: Name or service not known] SSH: Connecting with configuration [XXX] ... SSH: EXEC: STDOUT/STDERR from command [cd /mnt/www/ttmall_front_next tar -zxf tmp.tar.gz #nvm ls #nvm use v14.10.0 nvm use v16.13.2 node -v npm -v npm install --registry=https://registry.npm.taobao.org #npm install node-sass --unsafe-perm=true --allow-root #npm run build:stag npm run build:stag_gg #npm run build:stag_gg2 chown -R www.www /mnt/www/ttmall_front_next /usr/local/bin/pm2 delete ttmall_front_next /usr/local/bin/pm2 start npm --name ttmall_front_next --error log/error.log --output log/output.log -- run start_stag_gg ] ... Now using node v16.13.2 (npm v8.1.2) v16.13.2 8.1.2
解决方案建议
1. 检查PM2实际使用的Node.js版本
PM2可能未使用当前shell环境的Node.js版本,而是系统默认的低版本。
- 执行
pm2 show ttmall_front_next查看进程的Node路径。 - 启动PM2时指定高版本Node的路径,例如:
/usr/local/bin/pm2 start /path/to/nvm/versions/node/v16.13.2/bin/npm --name ttmall_front_next --error log/error.log --output log/output.log -- run start_stag_gg - 或先通过
which node获取当前nvm管理的Node路径,再替换到PM2启动命令中。
2. 清理缓存并重新安装依赖
高版本Node下的依赖缓存可能存在冲突:
rm -rf node_modules rm package-lock.json npm cache clean --force npm install --registry=https://registry.npm.taobao.org
完成后重新执行构建。
3. 调整Next.js版本
Next.js 13部分版本可能和特定Node.js版本存在兼容性问题:
- 升级到最新稳定版:
npm install next@latest - 或降级到已知兼容的版本(如v13.4.x)
4. 确保shell环境的Node版本全局生效
检查当前Node路径优先级,避免系统默认低版本覆盖nvm的版本:
- 执行
which node确认路径是否为nvm管理版本。 - 修改shell配置文件(如
~/.bashrc或~/.zshrc),添加:export PATH="$NVM_DIR/versions/node/v16.13.2/bin:$PATH" - 重新加载配置:
source ~/.bashrc
内容的提问来源于stack exchange,提问作者kratospan
相关产品推荐
相关产品推荐

