无法修复 switch 语句中缩进 case 语句的 eslint 规则

下面是我的卓越文本窗口的屏幕快照,显示了为 switch/case 语句抛出的 eslint 错误。我想必须缩进4个空格,如代码所示。

enter image description here

这里是 4的不同尝试,试图允许4个空格的缩进,通过修改。在我的反应应用程序中的 eslintrc 文件。我在谷歌上搜索了一个解决方案,看到了添加 switchCase 和 indentSwitchCase 的建议,但是我的。Eslintrc 规则是全空格的,而不是 camelcase,所以我添加了所有4个规则,以消除崇高文本的错误,但没有运气... 我做错了什么? ! ? !

enter image description here

编辑: 这是一个反应/MERN 应用程序,我使用崇高的文本作为我的编辑器。让我知道,如果我可以分享任何其他从我的。帮助 eslintrc 文件!

编辑2: 我试过这个:

"indent": ["error", 4, {SwitchCase: 1}]

... 但这是一个无效的缩进规则。 如何向缩进规则添加选项对象而不出错?

34498 次浏览

I just saw that you made an edit ("EDIT 2") to your answer.

Anyway I wanted to advise you exactly that option:

"indent": ["error", 4, { "SwitchCase": 1 }]

Why do you consider it "an invalid rule for indent"?

According to the docs, it is the correct way to set the desired indent for switch statements.

"SwitchCase" (default: 0) enforces indentation level for case clauses in switch statements.

The docs provide also [four examples]:

  • Indent of 2 spaces with SwitchCase set to 0 will not indent case clauses with respect to switch statements.
  • Indent of 2 spaces with SwitchCase set to 1 will indent case clauses with 2 spaces with respect to switch statements.
  • Indent of 2 spaces with SwitchCase set to 2 will indent case clauses with 4 spaces with respect to switch statements.
  • Indent of tab with SwitchCase set to 2 will indent case clauses with 2 tabs with respect to switch statements.

They are just examples, the fact that your target option object is not listed doesn't mean that it is not correct. And indeed it seems to be correct: ESLint Demo.

Your use case is actually included in the docs of the version 2.0.0 (no anchor to link directly, sorry, it it the last code block of the document):

/*eslint indent: [2, 4, {"SwitchCase": 1}]*/


switch(a){
case "a":
break;
case "b":
break;
}

In a typescript code-base, using TypeScript ESLint's @typescript-eslint/indent can solve the problem.

{
// note you must disable the base rule as it can report incorrect errors
"indent": "off",
"@typescript-eslint/indent": ["error"]
}

In the following example, ESLint's indent rule is causing errors in a typescript file.

ESLint indent rule error in a switch statement - Expected indentation of 4 spaces but found 6