node_modules 文件夹中可选链接运算符 (?.) 出现 Node / Typescript / tslint 错误

问题描述 投票:0回答:3

我有一个节点脚本,可以在高达 17 的节点版本上正常运行:

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

从节点版本 18 开始,它会出错,因为 @npmcli 使用可选的链接运算符:

$ 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 '.'

我在节点版本 19、20 和 21 上遇到类似的错误。我猜这与我的 typescript 或 tslint 设置有关,它不喜欢任何可选的链接运算符。我尝试忽略我的

tslint.json
文件中的任何 node_modules 文件夹,但它不能解决问题:

{
  "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"
    ]
  }
}

我的

tsconfig.json
文件:

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

有任何提示如何在我的设置中允许可选链接运算符吗?

node.js typescript tslint
3个回答
1
投票

您可以跳过node_modules文件夹,如下所示

{
  "compilerOptions": {
  "skipLibCheck": true
  },
}

命令行

tsc --skipLibCheck

  "include": [
  "src/*"
  ],
  "exclude": [
  "node_modules",
  "./node_modules",
  "./node_modules/*",
  "./node_modules/@types/node/index.d.ts",
  ]
}

1
投票

您可以更新您的

compilerOptions
以包含可选链接的特定规则。这将允许您保持严格模式并继续验证依赖关系。

你的

compilerOptions
看起来像这样:

{
  "compilerOptions": {
    "target": "ESNEXT",             
    "module": "commonjs",           
    "strict": true,
    "esModuleInterop": true,        
    "sourceMap": true,
    "lib": ["ESNext", "DOM", "ES2020.OptionalChaining", "ES2020.NullishCoalescing"]
  }
}

(之后您可能需要重建 TypeScript 项目(使用

npx tsc
)才能应用更改)


0
投票

似乎问题可能出在目标

esnext
上,这会阻止某些功能的转译。尝试将
target
语言设置为
es2020
(或更低)。

© www.soinside.com 2019 - 2024. All rights reserved.