为什么可选链在我的 Node REPL 中不起作用?

Har*_*aye 0 javascript syntax node.js optional-chaining

我从MDN中逐字复制粘贴的示例代码,但可选链接在我的节点(v12.13.0)REPL 中不起作用。抛出语法错误,指出问号后面的点无效。这是怎么回事 ?我已经在 React 应用程序中使用了这个表达式,它似乎工作得很好。

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};


const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

Run Code Online (Sandbox Code Playgroud)

met*_*bar 6

它仅适用于 Node 14,在 --harmony 下: 如何在 Node.js 12 中使用可选链

如果您想在节点中使用此功能,您可以使用 babel 可选链接插件: https://babeljs.io/docs/en/next/babel-plugin-syntax-optional-chaining.html