Eslint
规则 | Rules

brace-style

要求 Brace Style(大括号)

--fix命令行上的选项可以自动修复一些被这条规则反映的问题。

Brace风格与编程中的缩进风格密切相关,并描述了花括号相对于其控制语句和正文的位置。世界上可能有十几种支架,如果不是更多的话。

在一个真正的大括号的风格是在 JavaScrip 中最常见的主要款式,其中一个块的左大括号放在同一行及其相应的说明或声明中的一个。例如:

if (foo) { bar( } else { baz( }

一种真正的大括号风格的一种常见变体称为 Stroustrup,其中构造体中的else语句if-else以及catchfinally必须在前一个大括号之后在其自己的行上。例如:

if (foo) { bar( } else { baz( }

另一种风格叫做 Allman,其中所有的大括号预计将在他们自己的路线上没有任何额外的缩进。例如:

if (foo) { bar( } else { baz( }

尽管没有哪种风格比其他风格更好,但大多数开发人员都认为,在整个项目中保持一致的风格对于其长期可维护性来说非常重要。

规则细节

规则为块执行一致的括号样式。

选项

这条规则有字符串选项:

  • "1tbs" (默认)强制执行一个真正的大括号风格

规则具有异常的对象选项:

  • "allowSingleLine": true(默认false)允许一个块打开和关闭括号在同一行上

1tbs

"1tbs"规则的默认错误代码示例:

/*eslint brace-style: "error"*/ function foo() { return true; } if (foo) { bar( } try { somethingRisky( } catch(e) { handleError( } if (foo) { bar( } else { baz( }

具有默认选项"1tbs"的规则正确代码示例:

/*eslint brace-style: "error"*/ function foo() { return true; } if (foo) { bar( } if (foo) { bar( } else { baz( } try { somethingRisky( } catch(e) { handleError( } // when there are no braces, there are no problems if (foo) bar( else if (baz) boom(

"1tbs", { "allowSingleLine": true }选项的规则正确代码示例包含以下:

/*eslint brace-style: ["error", "1tbs", { "allowSingleLine": true }]*/ function nop() { return; } if (foo) { bar( } if (foo) { bar( } else { baz( } try { somethingRisky( } catch(e) { handleError( }

stroustrup

"stroustrup"选项的规则错误代码示例包含以下:

/*eslint brace-style: ["error", "stroustrup"]*/ function foo() { return true; } if (foo) { bar( } try { somethingRisky( } catch(e) { handleError( } if (foo) { bar( } else { baz( }

"stroustrup"选项的规则正确代码示例包含以下:

/*eslint brace-style: ["error", "stroustrup"]*/ function foo() { return true; } if (foo) { bar( } if (foo) { bar( } else { baz( } try { somethingRisky( } catch(e) { handleError( } // when there are no braces, there are no problems if (foo) bar( else if (baz) boom(

使用"stroustrup", { "allowSingleLine": true }选项的规则正确代码示例包含以下:

/*eslint brace-style: ["error", "stroustrup", { "allowSingleLine": true }]*/ function nop() { return; } if (foo) { bar( } if (foo) { bar( } else { baz( } try { somethingRisky( } catch(e) { handleError( }

allman

使用"allman"选项的规则错误代码示例包含以下:

/*eslint brace-style: ["error", "allman"]*/ function foo() { return true; } if (foo) { bar( } try { somethingRisky( } catch(e) { handleError( } if (foo) { bar( } else { baz( }

"allman"选项的规则正确代码示例包含以下:

/*eslint brace-style: ["error", "allman"]*/ function foo() { return true; } if (foo) { bar( } if (foo) { bar( } else { baz( } try { somethingRisky( } catch(e) { handleError( } // when there are no braces, there are no problems if (foo) bar( else if (baz) boom(

"allman", { "allowSingleLine": true }规则的正确代码示例包含以下选项:

/*eslint brace-style: ["error", "allman", { "allowSingleLine": true }]*/ function nop() { return; } if (foo) { bar( } if (foo) { bar( } else { baz( } try { somethingRisky( } catch(e) { handleError( }

何时不使用它

如果您不想执行特定的大括号样式,请不要启用此规则。

进一步阅读

版本

这个规则在 ESLint 0.0.7 中引入。

资源