max-classes-per-file

强制每个文件的最大类数

包含多个类的文件通常会导致可导航性较差且结构不良的代码库。最佳实践是将每个文件限制为单一职责。

¥Files containing multiple classes can often result in a less navigable and poorly structured codebase. Best practice is to keep each file limited to a single responsibility.

规则详情

¥Rule Details

该规则强制每个文件只能包含特定数量的类,不能更多。

¥This rule enforces that each file may contain only a particular number of classes and no more.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint max-classes-per-file: "error"*/

class Foo {}
class Bar {}

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint max-classes-per-file: "error"*/

class Foo {}

选项

¥Options

此规则可以使用对象或数字进行配置。

¥This rule may be configured with either an object or a number.

如果选项是一个对象,它可能包含以下一项或两项:

¥If the option is an object, it may contain one or both of:

  • ignoreExpressions:忽略类表达式的布尔选项(默认为 false)。

    ¥ignoreExpressions: a boolean option (defaulted to false) to ignore class expressions.

  • max:一个数字选项(默认为 1)来指定类的最大数量。

    ¥max: a numeric option (defaulted to 1) to specify the maximum number of classes.

例如:

¥For example:

{
    "max-classes-per-file": ["error", 1]
}
{
    "max-classes-per-file": [
        "error",
        { "ignoreExpressions": true, "max": 2 }
    ]
}

此规则的正确代码示例(max 选项设置为 2):

¥Examples of correct code for this rule with the max option set to 2:

在线运行
/* eslint max-classes-per-file: ["error", 2] */

class Foo {}
class Bar {}

此规则的正确代码示例(ignoreExpressions 选项设置为 true):

¥Examples of correct code for this rule with the ignoreExpressions option set to true:

在线运行
/* eslint max-classes-per-file: ["error", { ignoreExpressions: true }] */

class VisitorFactory {
    forDescriptor(descriptor) {
        return class {
            visit(node) {
                return `Visiting ${descriptor}.`;
            }
        };
    }
}

版本

此规则是在 ESLint v5.0.0-alpha.3 中引入。

资源

ESLint 中文网
粤ICP备13048890号