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

Node 18+版本中node_modules可选链运算符语法错误求助

问题

我的Node脚本在Node 17及以下版本可正常运行,执行流程如下:

$ nvm use 17
Now using node v17.9.1 (npm v8.11.0)
$ cd src
$ npx tsc
$ npx node parser.js
$ cd ..

但升级至Node 18、19、20、21版本时,执行npx tsc命令出现语法错误,报错信息显示@npmcli/config中使用的可选链运算符(?.)为意外符号:

$ nvm use 18
Now using node v18.16.0 (npm v9.5.1)
$ cd src
$ npx tsc
/Users/mles/.nvm/versions/node/v18.16.0/lib/node_modules/npm/node_modules/@npmcli/config/lib/index.js:485
        const raw = this.data.get(problem.where).raw?.[problem.from]
                                                     ^

SyntaxError: Unexpected token '.'

推测问题与TypeScript或TSLint配置有关,已尝试在tslint.json中排除node_modules目录,但未解决问题。相关配置文件如下:

TSLint配置

{  
  "defaultSeverity": "error",  
  "extends": [    
    "tslint:recommended"  
  ],  
  "jsRules": {},  
  "rules": {    
    "no-console": false,    
    "object-literal-sort-keys": [      
      true,      
      "match-declaration-order"    
    ],    
    "max-line-length": [      
      true,      
      200    
    ],    
    "typedef": [      
      true,      
      "member-variable-declaration",      
      "variable-declaration"    
    ]  
  },  
  "rulesDirectory": [],  
  "compilerOptions": {    
    "skipLibCheck": true  
  },  
  "linterOptions": {    
    "exclude": [        
      "node_modules"    
    ]  
  }
}

TypeScript配置

{  
  "compilerOptions": {    
    "target": "ESNEXT",              
    "module": "commonjs",           
    "strict": true,                 
    "esModuleInterop": true,        
    "sourceMap": true  
  }
}

请问如何调整配置以允许可选链运算符?

解决方法

1. 改用本地TypeScript版本

当前用npx tsc调用的是全局TS版本,可能和项目依赖不兼容。建议在项目本地安装TypeScript,使用本地版本执行编译:

  • 安装本地TS:
npm install typescript --save-dev
  • 执行本地TS编译:
npx tsc --version # 确认使用本地版本
npm run build # 或在package.json中配置"build": "tsc",再执行该命令

2. 修正TypeScript编译配置

在tsconfig.json中补充配置,确保TS正确识别可选链运算符:

{
  "compilerOptions": {
    "target": "ES2020", // 可选链是ES2020特性,指定该版本更稳妥
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "lib": ["ES2020"], // 引入ES2020标准库
    "skipLibCheck": true, // 跳过第三方库的类型检查,避免语法冲突
    "allowJs": false // 仅编译TS文件,不处理JS文件
  },
  "exclude": ["node_modules"] // 明确排除node_modules目录
}

3. 修复TSLint配置(若继续使用)

TSLint已被官方弃用,建议迁移到ESLint;若暂时保留,需修正配置:

  • 移除tslint.json中的compilerOptions字段,该配置应放在tsconfig.json中
  • 确认linterOptions.exclude已包含node_modules,避免检查第三方JS文件

4. 清理缓存并重装依赖

缓存可能导致版本冲突,执行以下命令清理:

rm -rf node_modules package-lock.json
npm install

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:22:24