如何在 Node.js 12中使用可选链接

可选链接(obj?.param1?.param2)似乎是一个很棒的特性,我真的希望看到它的实现,并最终摆脱嵌套的如果,任意函数和什么不这样一个简单的操作。

但是有一个问题,它不工作。我更新到 Node 12,但是仍然得到一个错误:

var dude = res?.param?.params[0]
SyntaxError: Unexpected token '.'

或者

var dude = res.param?.params[0]
SyntaxError: Unexpected token '.'

有什么问题吗?

我是否需要更改一些语言配置或下载一个库来启用这个特性?还是只是还没有出来?

79767 次浏览

Optional chaining is currently not supported in Node.js version 13 and below. It will be supported from Node.js version 14 and most of the browsers as it is moved to Stage 4. Currently, few platforms are supporting it. You can find the list of platforms supporting optional chaining in the given link. You can enable optional using --harmony flag.

The spec for the optional chaining feature was just promoted to Stage 4 (Finished) on December 22, 2019. Node 12 came out before the spec was final - and so did Node 13, for that matter.

According to node.green, optional chaining will be supported starting with Node 14, but will still require the --harmony flag. (This seems to conflict with Node's description of the --harmony flag - V8's shipping features aren't supposed to require the flag - so I'm not sure what to make of that.) Still, whether it needs a flag or not, I wouldn't expect to see the feature until the Node 14 release around April 2020.

If you want to play with optional chaining today, your best bet is to use TypeScript (which added optional chaining in version 3.7) or a preprocessor like Babel.

I was able to use nodejs v13.7.0 with --harmony flag.

node --harmony myCode.js

Dinah

undefined

undefined

//myCode.js


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


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


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

Optional Chaining will be implemented with Node.js v14, which will be released on 20/04/2020. By now, you may use Babel with @babel/plugin-proposal-optional-chaining.

If you're still having this issue, check the node version you're using node --version.

If you have nvm, make sure you're using a node version that implements the operator that is giving an error.

e.g.

nvm install 15.8
nvm use 15.8