nonblock-statement-body-position
在编写 if、else、while、do-while 和 for 语句时,语句体可以是单个语句,而不是代码块。强制执行这些单个语句的一致位置可能很有用。
例如,一些开发者避免编写类似这样的代码
js
if (foo)
bar();如果另一个开发者尝试将 baz(); 添加到 if 语句中,他们可能会错误地将代码更改为
js
if (foo)
bar();
baz(); // this line is not in the `if` statement!为了避免这个问题,可以要求所有单行 if 语句直接出现在条件之后,没有换行符
js
if (foo) bar();规则详细信息
此规则旨在强制执行单行语句的一致位置。
请注意,此规则不会强制执行单行语句的通用使用。如果您想禁止单行语句,请改用 curly 规则。
选项
此规则接受一个字符串选项
"beside"(默认)禁止在单行语句之前换行。"below"要求在单行语句之前换行。"any"不强制执行单行语句的位置。
此外,该规则接受一个可选的对象选项,其中包含一个 "overrides" 键。这可以用来指定特定语句的位置,这些语句会覆盖默认设置。例如
"beside", { "overrides": { "while": "below" } }要求所有单行语句出现在其父语句的同一行,除非父语句是while语句,在这种情况下,单行语句必须不在同一行。"below", { "overrides": { "do": "any" } }禁止所有单行语句出现在其父语句的同一行,除非父语句是do-while语句,在这种情况下,单行语句的位置不受限制。
使用默认 "beside" 选项时,此规则的错误代码示例
js
/* eslint @stylistic/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" 选项时,此规则的正确代码示例
js
/* eslint @stylistic/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" 选项时,此规则的错误代码示例
js
/* eslint @stylistic/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" 选项时,此规则的正确代码示例
js
/* eslint @stylistic/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" } } 规则时,此规则的错误代码示例
js
/* eslint @stylistic/nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] */
if (foo)
bar();
while (foo) bar(); 错误
使用 "beside", { "overrides": { "while": "below" } } 规则时,此规则的正确代码示例
js
/* eslint @stylistic/nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] */
if (foo) bar();
while (foo)
bar(); 正确
何时不使用它
如果您不关心单行语句的一致位置,则不应启用此规则。如果您对 curly 规则使用 "all" 选项,也可以禁用此规则,因为这将完全禁止单行语句。