You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级Node与AWS CDK后aws-ec2出现可选链操作符语法错误

升级NX、Node及AWS CDK后,ts-node执行脚本因可选链操作符报错的解决方法

问题场景

升级NX及相关依赖、将Node版本从12.20.2更新至14.15.0,并同步升级AWS CDK包后,执行以下命令时触发错误:

npx env-cmd -f pipeline.json npx ts-node --project ./scripts/tsconfig.json ./apps/cloud-infrastructure/src/bin/pre-build.ts

错误根源为aws-ec2包中的可选链操作符(?.)无法被正确解析,尝试切换其他Node版本未解决问题。

相关TS配置文件

tsconfig.base.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom",
      "esnext.asynciterable"
    ],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true
  },
  "files": [
    "./polyfills.localize.ts"
  ],
  "exclude": [
    "node_modules",
    "tmp"
  ]
}

子tsconfig(./scripts/tsconfig.json)

{
  "extends": "../tsconfig.base.json",
  "compilerOptions": {
    "types": ["node", "jest"],
    "lib": ["ES6", "ES2017", "es2015", "ES2020.Promise"],
    "module": "CommonJS"
  },
  "include": ["**/*.ts"]
}

解决步骤

  1. 升级TypeScript版本
    可选链是TypeScript 3.7+的特性,先检查项目TS版本:
npm list typescript

若版本低于3.7,执行升级:

npm install typescript@^4.0.0 --save-dev
  1. 调整TS编译配置
    可选链对应ES2020标准,需修改子tsconfig的编译选项:
  • 在compilerOptions中添加target: "es2020"(覆盖base配置的es2015)
  • 更新lib数组,加入es2020:
    "lib": ["ES6", "ES2017", "es2015", "ES2020", "ES2020.Promise"],
    
  1. 配置ts-node专属编译规则
    在子tsconfig中添加ts-node的专属配置,确保它能正确解析ES2020语法:
"ts-node": {
  "transpileOnly": true,
  "compilerOptions": {
    "target": "es2020",
    "module": "CommonJS"
  }
}

也可以直接在执行命令中显式指定编译目标:

npx env-cmd -f pipeline.json npx ts-node --project ./scripts/tsconfig.json --target es2020 ./apps/cloud-infrastructure/src/bin/pre-build.ts
  1. 校验AWS CDK版本兼容性
    确认升级后的AWS CDK版本与Node 14、TypeScript版本适配,若存在兼容问题,回退到官方文档标注的适配版本。

  2. 清理依赖缓存
    删除旧依赖文件后重新安装,避免缓存冲突:

rm -rf node_modules package-lock.json
npm install

内容的提问来源于stack exchange,提问作者Shailesh Ladumor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:15:39