版本

nonblock-statement-body-position

强制单行语句的位置

🔧 可修复

此规则报告的一些问题可以通过 --fix 命令行 选项自动修复

重要提示

此规则在 ESLint v8.53.0 中已弃用。请使用 @stylistic/eslint-plugin-js 中的对应规则

了解更多

在编写 ifelsewhiledo-whilefor 语句时,主体可以是单个语句而不是代码块。强制这些单语句的一致位置可能很有用。

例如,一些开发者避免编写像这样的代码

if (foo)
  bar();

如果另一个开发者尝试将 baz(); 添加到 if 语句中,他们可能会错误地将代码更改为

if (foo)
  bar();
  baz(); // this line is not in the `if` statement!

为了避免这个问题,有人可能要求所有单行 if 语句都直接出现在条件之后,没有换行符

if (foo) bar();

规则详情

此规则旨在强制单行语句的一致位置。

请注意,此规则不强制使用单行语句。如果您想禁止使用单行语句,请改用 curly 规则。

选项

此规则接受一个字符串选项

  • "beside" (默认) 禁止在单行语句之前换行。
  • "below" 要求在单行语句之前换行。
  • "any" 不强制单行语句的位置。

此外,该规则接受一个带有 "overrides" 键的可选对象选项。这可以用于为特定的语句指定一个位置,以覆盖默认值。例如

  • "beside", { "overrides": { "while": "below" } } 要求所有单行语句都与其父语句在同一行,除非父语句是 while 语句,在这种情况下,单行语句不得与其在同一行。
  • "below", { "overrides": { "do": "any" } } 禁止所有单行语句与其父语句在同一行,除非父语句是 do-while 语句,在这种情况下,不强制单行语句的位置。

使用默认 "beside" 选项时,错误代码示例

在 Playground 中打开
/* eslint nonblock-statement-body-position: ["error", "beside"] */

if (foo)
  bar();
else
  baz();

while (foo)
  bar();

for (let i = 1; i < foo; i++)
  bar();

do
  bar();
while (foo)

使用默认 "beside" 选项时,正确代码示例

在 Playground 中打开
/* eslint nonblock-statement-body-position: ["error", "beside"] */

if (foo) bar();
else baz();

while (foo) bar();

for (let i = 1; i < foo; i++) bar();

do bar(); while (foo)

if (foo) { // block statements are always allowed with this rule
  bar();
} else {
  baz();
}

使用 "below" 选项时,错误代码示例

在 Playground 中打开
/* eslint nonblock-statement-body-position: ["error", "below"] */

if (foo) bar();
else baz();

while (foo) bar();

for (let i = 1; i < foo; i++) bar();

do bar(); while (foo)

使用 "below" 选项时,正确代码示例

在 Playground 中打开
/* eslint nonblock-statement-body-position: ["error", "below"] */

if (foo)
  bar();
else
  baz();

while (foo)
  bar();

for (let i = 1; i < foo; i++)
  bar();

do
  bar();
while (foo)

if (foo) {
  // Although the second `if` statement is on the same line as the `else`, this is a very common
  // pattern, so it's not checked by this rule.
} else if (bar) {
}

使用 "beside", { "overrides": { "while": "below" } } 规则时,错误代码示例

在 Playground 中打开
/* eslint nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] */

if (foo)
  bar();

while (foo) bar();

使用 "beside", { "overrides": { "while": "below" } } 规则时,正确代码示例

在 Playground 中打开
/* eslint nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] */

if (foo) bar();

while (foo)
  bar();

何时不使用

如果您不关心单行语句的一致位置,则不应启用此规则。如果您为 curly 规则使用 "all" 选项,也可以禁用此规则,因为这将完全禁止单行语句。

版本

此规则在 ESLint v3.17.0 中引入。

延伸阅读

Avatar image for jscs-dev.github.io
JSCS
jscs-dev.github.io

资源

更改语言