我有一个节点脚本,可以在高达 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_modules文件夹,如下所示
{
"compilerOptions": {
"skipLibCheck": true
},
}
或
命令行
tsc --skipLibCheck
或
"include": [
"src/*"
],
"exclude": [
"node_modules",
"./node_modules",
"./node_modules/*",
"./node_modules/@types/node/index.d.ts",
]
}
您可以更新您的
compilerOptions
以包含可选链接的特定规则。这将允许您保持严格模式并继续验证依赖关系。
你的
compilerOptions
看起来像这样:
{
"compilerOptions": {
"target": "ESNEXT",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"sourceMap": true,
"lib": ["ESNext", "DOM", "ES2020.OptionalChaining", "ES2020.NullishCoalescing"]
}
}
(之后您可能需要重建 TypeScript 项目(使用
npx tsc
)才能应用更改)