问题
I am looking for the relevant eslint rules for
- @babel/plugin-proposal-optional-chaining
- @babel/plugin-proposal-nullish-coalescing-operator
My editor highlights in red when I do the following
const baz = obj?.foo?.bar?.baz; // 42
const safe = obj?.qux?.baz; // undefined
const foo = obj.baz ?? 'default'; // default
// eslint-disable-next-line no-console
console.log('baz', baz);
// eslint-disable-next-line no-console
console.log('safe', safe);
// eslint-disable-next-line no-console
console.log('foo', foo);
The code works properly, but eslint highlights my code in red.
Reference:
- https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
- https://babeljs.io/docs/en/babel-plugin-proposal-nullish-coalescing-operator
回答1:
Nullish coalescing operator is natively supported starting from eslint>=7.5.0
.
The easiest is set ES2020 in your package.json:
{
"eslintConfig":
{
"parserOptions":
{
"ecmaVersion": 2020
}
}
}
回答2:
add the following config to your eslint
:
"parser": "babel-eslint"
回答3:
Have you tried setting the parser on your eslint config to "babel-eslint"? https://www.npmjs.com/package/babel-eslint It's the recommended parser when using experimental features not supported in eslint yet.
回答4:
You have to use this plugin: https://github.com/babel/eslint-plugin-babel
You can then disable the original eslint-rule and enable the babel version of it, which will then show no false errors. Your eslint-config could then look like this:
{
parser: "babel-eslint",
rules: {
"no-unused-expressions": 0,
"babel/no-unused-expressions": 1
},
plugins: ["babel"]
}
来源:https://stackoverflow.com/questions/57378411/eslint-rule-for-optional-chaining-nullish-coalescing-operator