版本

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

資源

變更語言