繁体   English   中英

使用 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM