使用 Babel 转译 Node.js + TypeScript 应用程序:为什么它不使用可选链接?

Transpiling a Node.js + TypeScript app with Babel: why it's not using optional chaining?

我正在试验 Babel 以更好地理解它的工作原理。我用 Node.js 和 TypeScript 创建了一个简单的 API。当我转译代码并且服务器正常运行时,一切正常。不过我有一个问题:在节点 v14.15.3 中支持可选链接,所以为什么当我构建时使用:

rm -rf build/ && babel src --source-maps --extensions '.js,.ts,.tsx' --ignore '**/*.test.ts' -d build

无论我是什么版本的节点运行在shell(通过使用nvm - v12.18.3v14.15.3)以下行

console.log(x?.ciao ?? 10)

它总是被转译为

console.log((_x$ciao = x === null || x === void 0 ? void 0 : x.ciao) !== null && _x$ciao !== void 0 ? _x$ciao : 10);

我希望它在转译后的代码中使用 .???,因为它们受支持。我错过了什么?

我也尝试删除 @babel/preset-typescript 预设并用单个文件进行了测试,但代码仍按上述方式转译。

我的 .babelrc 文件:

{
  "presets": ["@babel/preset-typescript", ["@babel/preset-env", { "shippedProposals": true }]],
  "plugins": [
    [
      "module-resolver",
      {
        "root": "./src",
        "alias": {
          "@root": ["./"],
          "@src": ["./src"]
        },
        "extensions": [".js", ".ts"]
      }
    ]
  ],
  "sourceMaps": true
}

要使其正常工作,请使用 "targets": { "node": 14 },如以下 .babelrc 示例所示。这不会转译 .???,因为它们在节点 14.x.

中受支持
{
  "presets": [
    "@babel/preset-typescript",
    [
      "@babel/preset-env",
      {
        "targets": { "node": 14 }
      }
    ]
  ],
  "plugins": [
    [
      "module-resolver",
      {
        "root": "./src",
        "alias": {
          "@root": ["./"],
          "@src": ["./src"]
        },
        "extensions": [".js", ".ts"]
      }
    ]
  ],
  "sourceMaps": true
}