semi

要求或禁止使用分号而不是 ASI

🔧 Fixable

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

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

¥This rule was deprecated in ESLint v8.53.0. Please use the corresponding rule in @stylistic/eslint-plugin-js.

JavaScript 不需要在每条语句的末尾使用分号。在许多情况下,JavaScript 引擎可以确定分号应该在某个位置并自动添加它。此功能称为自动分号插入 (ASI),被认为是 JavaScript 中最具争议的功能之一。例如,以下行都是有效的:

¥JavaScript doesn’t require semicolons at the end of each statement. In many cases, the JavaScript engine can determine that a semicolon should be in a certain spot and will automatically add it. This feature is known as automatic semicolon insertion (ASI) and is considered one of the more controversial features of JavaScript. For example, the following lines are both valid:

var name = "ESLint"
var website = "eslint.org";

在第一行,JavaScript 引擎会自动插入一个分号,所以这不被认为是语法错误。JavaScript 引擎仍然知道如何解释该行,并且知道行尾表示语句的结束。

¥On the first line, the JavaScript engine will automatically insert a semicolon, so this is not considered a syntax error. The JavaScript engine still knows how to interpret the line and knows that the line end indicates the end of the statement.

在关于 ASI 的争论中,通常有两种思想流派。首先是我们应该将 ASI 视为不存在,并始终手动包含分号。基本原理是始终包含分号比尝试记住何时需要或不需要分号更容易,从而降低了引入错误的可能性。

¥In the debate over ASI, there are generally two schools of thought. The first is that we should treat ASI as if it didn’t exist and always include semicolons manually. The rationale is that it’s easier to always include semicolons than to try to remember when they are or are not required, and thus decreases the possibility of introducing an error.

但是,对于使用分号的人来说,ASI 机制有时会很棘手。例如,考虑以下代码:

¥However, the ASI mechanism can sometimes be tricky to people who are using semicolons. For example, consider this code:

return
{
    name: "ESLint"
};

这可能看起来像一个返回对象字面量的 return 语句,但是,JavaScript 引擎会将这段代码解释为:

¥This may look like a return statement that returns an object literal, however, the JavaScript engine will interpret this code as:

return;
{
    name: "ESLint";
}

实际上,在 return 语句之后插入了一个分号,导致它下面的代码(块内的标记字面)无法访问。此规则和 no-unreachable 规则将保护你的代码免受此类情况的影响。

¥Effectively, a semicolon is inserted after the return statement, causing the code below it (a labeled literal inside a block) to be unreachable. This rule and the no-unreachable rule will protect your code from such cases.

争论的另一面是那些说由于分号是自动插入的,它们是可选的,不需要手动插入。但是,对于不使用分号的人来说,ASI 机制也很棘手。例如,考虑以下代码:

¥On the other side of the argument are those who say that since semicolons are inserted automatically, they are optional and do not need to be inserted manually. However, the ASI mechanism can also be tricky to people who don’t use semicolons. For example, consider this code:

var globalCounter = { }

(function () {
    var n = 0
    globalCounter.increment = function () {
        return ++n
    }
})()

在此示例中,不会在第一行之后插入分号,从而导致运行时错误(因为将空对象作为函数调用)。no-unexpected-multiline 规则可以保护你的代码免受此类情况的影响。

¥In this example, a semicolon will not be inserted after the first line, causing a run-time error (because an empty object is called as if it’s a function). The no-unexpected-multiline rule can protect your code from such cases.

尽管 ASI 允许你对编码风格有更多的自由,但它也可能使你的代码以意想不到的方式运行,无论你是否使用分号。因此,最好知道 ASI 何时发生以及何时不发生,并让 ESLint 保护你的代码免受这些潜在的意外情况的影响。简而言之,正如 Isaac Schlueter 曾经描述的那样,一个 \n 字符总是结束一个语句(就像一个分号),除非满足以下条件之一:

¥Although ASI allows for more freedom over your coding style, it can also make your code behave in an unexpected way, whether you use semicolons or not. Therefore, it is best to know when ASI takes place and when it does not, and have ESLint protect your code from these potentially unexpected cases. In short, as once described by Isaac Schlueter, a \n character always ends a statement (just like a semicolon) unless one of the following is true:

  1. 该语句有一个未闭合的括号、数组字面量或对象字面量,或者以某种不是结束语句的有效方式的其他方式结束。(例如,以 ., 结尾。)

    ¥The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with . or ,.)

  2. 该行是 --++(在这种情况下,它将递减/递增下一个令牌。)

    ¥The line is -- or ++ (in which case it will decrement/increment the next token.)

  3. 它是 for()while()doif()else,且没有 {

    ¥It is a for(), while(), do, if(), or else, and there is no {

  4. 下一行以 [(+*/-,. 或其他只能在单个表达式中的两个标记之间找到的二元运算符开头。

    ¥The next line starts with [, (, +, *, /, -, ,, ., or some other binary operator that can only be found between two tokens in a single expression.

规则详情

¥Rule Details

此规则强制使用一致的分号。

¥This rule enforces consistent use of semicolons.

选项

¥Options

该规则有两个选项,一个字符串选项和一个对象选项。

¥This rule has two options, a string option and an object option.

字符串选项:

¥String option:

  • "always"(默认)需要在语句末尾加分号

    ¥"always" (default) requires semicolons at the end of statements

  • "never" 不允许在语句末尾使用分号(除非是为了消除以 [(/+- 开头的语句的歧义)

    ¥"never" disallows semicolons at the end of statements (except to disambiguate statements beginning with [, (, /, +, or -)

对象选项("always" 时):

¥Object option (when "always"):

  • "omitLastInOneLineBlock": true 不允许块中最后一个分号的大括号(以及块的内容)位于同一行

    ¥"omitLastInOneLineBlock": true disallows the last semicolon in a block in which its braces (and therefore the content of the block) are in the same line

  • "omitLastInOneLineClassBody": true 不允许类主体中最后一个分号的大括号(以及类主体的内容)位于同一行

    ¥"omitLastInOneLineClassBody": true disallows the last semicolon in a class body in which its braces (and therefore the content of the class body) are in the same line

对象选项("never" 时):

¥Object option (when "never"):

  • 如果下一行以 [(/+- 开头,"beforeStatementContinuationChars": "any"(默认)将忽略语句末尾的分号(或缺少分号)。

    ¥"beforeStatementContinuationChars": "any" (default) ignores semicolons (or lacking semicolon) at the end of statements if the next line starts with [, (, /, +, or -.

  • 如果下一行以 [(/+- 开头,则 "beforeStatementContinuationChars": "always" 要求在语句末尾使用分号。

    ¥"beforeStatementContinuationChars": "always" requires semicolons at the end of statements if the next line starts with [, (, /, +, or -.

  • "beforeStatementContinuationChars": "never" 不允许在语句末尾使用分号,如果它不会造成 ASI 危险,即使下一行以 [(/+- 开头。

    ¥"beforeStatementContinuationChars": "never" disallows semicolons at the end of statements if it doesn’t make ASI hazard even if the next line starts with [, (, /, +, or -.

注意:beforeStatementContinuationChars 不适用于类字段,因为类字段不是语句。

¥Note: beforeStatementContinuationChars does not apply to class fields because class fields are not statements.

always

使用默认 "always" 选项的此规则的错误代码示例:

¥Examples of incorrect code for this rule with the default "always" option:

在线运行
/*eslint semi: ["error", "always"]*/

var name = "ESLint"

object.method = function() {
    // ...
}

class Foo {
    bar = 1
}

使用默认 "always" 选项的此规则的正确代码示例:

¥Examples of correct code for this rule with the default "always" option:

在线运行
/*eslint semi: "error"*/

var name = "ESLint";

object.method = function() {
    // ...
};

class Foo {
    bar = 1;
}

omitLastInOneLineBlock

使用 "always", { "omitLastInOneLineBlock": true } 选项的此规则的附加正确代码示例:

¥Examples of additional correct code for this rule with the "always", { "omitLastInOneLineBlock": true } options:

在线运行
/*eslint semi: ["error", "always", { "omitLastInOneLineBlock": true}] */

if (foo) { bar() }

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

function f() { bar(); baz() }

class C {
    foo() { bar(); baz() }

    static { bar(); baz() }
}

omitLastInOneLineClassBody

使用 "always", { "omitLastInOneLineClassBody": true } 选项的此规则的附加正确代码示例:

¥Examples of additional correct code for this rule with the "always", { "omitLastInOneLineClassBody": true } options:

在线运行
/*eslint semi: ["error", "always", { "omitLastInOneLineClassBody": true}] */

export class SomeClass{
    logType(){
        console.log(this.type);
        console.log(this.anotherType);
    }
}

export class Variant1 extends SomeClass{type=1}
export class Variant2 extends SomeClass{type=2; anotherType=3}

never

使用 "never" 选项的此规则的错误代码示例:

¥Examples of incorrect code for this rule with the "never" option:

在线运行
/*eslint semi: ["error", "never"]*/

var name = "ESLint";

object.method = function() {
    // ...
};

class Foo {
    bar = 1;
}

使用 "never" 选项的此规则的正确代码示例:

¥Examples of correct code for this rule with the "never" option:

在线运行
/*eslint semi: ["error", "never"]*/

var name = "ESLint"

object.method = function() {
    // ...
}

var name = "ESLint"

;(function() {
    // ...
})()

import a from "a"
(function() {
    // ...
})()

import b from "b"
;(function() {
    // ...
})()

class Foo {
    bar = 1
}

beforeStatementContinuationChars

使用 "never", { "beforeStatementContinuationChars": "always" } 选项的此规则的其他错误代码示例:

¥Examples of additional incorrect code for this rule with the "never", { "beforeStatementContinuationChars": "always" } options:

在线运行
/*eslint semi: ["error", "never", { "beforeStatementContinuationChars": "always"}] */
import a from "a"

(function() {
    // ...
})()

使用 "never", { "beforeStatementContinuationChars": "never" } 选项的此规则的其他错误代码示例:

¥Examples of additional incorrect code for this rule with the "never", { "beforeStatementContinuationChars": "never" } options:

在线运行
/*eslint semi: ["error", "never", { "beforeStatementContinuationChars": "never"}] */
import a from "a"

;(function() {
    // ...
})()

何时不使用

¥When Not To Use It

如果你不想以任何特定方式强制使用分号(或省略),则可以关闭此规则。

¥If you do not want to enforce semicolon usage (or omission) in any particular way, then you can turn this rule off.

版本

此规则是在 ESLint v0.0.6 中引入。

进阶读物

资源