Skip to content

useNamingConvention

诊断类别:lint/style/useNamingConvention

¥Diagnostic Category: lint/style/useNamingConvention

自从:v1.0.0

¥Since: v1.0.0

来源:

¥Sources:

强制 JavaScript 和 TypeScript 文件名的命名约定。

¥Enforce naming conventions for everything across a codebase.

强制 命名约定 有助于保持代码库的一致性,并在考虑变量的名称 case 时减少开销。

¥Enforcing naming conventions helps to keep the codebase consistent, and reduces overhead when thinking about the name case of a variable.

以下部分描述了规则强制执行的默认约定。你还可以使用 规则选项 强制执行自定义约定。

¥The following section describes the default conventions enforced by the rule. You can also enforce custom conventions with the rule options.

¥Naming conventions

所有名称都可以用下划线 _ 和美元符号 $ 作为前缀和后缀。

¥All names can be prefixed and suffixed by underscores _ and dollar signs $.

¥Variable and parameter names

所有变量和函数参数都在 camelCasePascalCase 中。CLI 现在能够自动搜索和解析 camelCase ()。

¥All variables and function parameters are in camelCase or PascalCase. Catch parameters are in camelCase.

此外,声明为 constvar 的全局变量可能在 CONSTANT_CASE 中。全局变量在模块或脚本级别声明。在 TypeScript namespace 中声明的变量也被视为全局变量。

¥Additionally, global variables declared as const or var may be in CONSTANT_CASE. Global variables are declared at module or script level. Variables declared in a TypeScript namespace are also considered global.

function f(param, _unusedParam) {
let localValue = 0;
try {
/* ... */
} catch (customError) {
/* ... */
}
}
export const A_CONSTANT = 5;
let aVariable = 0;
export namespace ns {
export const ANOTHER_CONSTANT = "";
}

不正确名称的示例:

¥Examples of incorrect names:

let a_value = 0;
code-block.js:1:5 lint/style/useNamingConvention  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This let name should be in camelCase or PascalCase.

> 1 │ let a_value = 0;
^^^^^^^
2 │

Safe fix: Rename this symbol in camelCase.

1 - let·a_value·=·0;
1+ let·aValue·=·0;
2 2

const fooYPosition = 0;
code-block.js:1:7 lint/style/useNamingConvention ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Two consecutive uppercase characters are not allowed in camelCase because strictCase is set to true.

> 1 │ const fooYPosition = 0;
^^^^^^^^^^^^
2 │

If you want to use consecutive uppercase characters in camelCase, then set the strictCase option to false.
See the rule options for more details.

function f(FIRST_PARAM) {}
code-block.js:1:12 lint/style/useNamingConvention  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This function parameter name should be in camelCase or PascalCase.

> 1 │ function f(FIRST_PARAM) {}
^^^^^^^^^^^
2 │

Safe fix: Rename this symbol in camelCase.

1 - function·f(FIRST_PARAM)·{}
1+ function·f(firstParam)·{}
2 2

¥Function names

  • function 名称在 camelCasePascalCase 中。

    ¥A function name is in camelCase or PascalCase.

  • 全局 function 也可以在 UPPERCASE 中。这允许支持需要某些功能才能使用有效 HTTP 方法名称 的框架。

    ¥A global function can also be in UPPERCASE. This allows supporting the frameworks that require some function to use valid HTTP method names.

function trimString(s) { /*...*/ }
function Component() {
return <div></div>;
}
export function GET() { /*...*/ }

¥TypeScript enum names

TypeScript enum 名称在 PascalCase 中。

¥A TypeScript enum name is in PascalCase.

enum 成员默认在 PascalCase 中。但是,你可以配置 enum 成员的 case。有关更多详细信息,请参阅 options

¥enum members are by default in PascalCase. However, you can configure the case of enum members. See options for more details.

enum Status {
Open,
Close,
}

¥Classes

class Person {
static MAX_FRIEND_COUNT = 256;
static get SPECIAL_PERSON_INSTANCE() { /*...*/ }
initializedProperty = 0;
specialMethod() {}
}

TypeScript type 别名和 interface

Section titled TypeScript type 别名和 interface

¥TypeScript type aliases and interface

  • type 别名或接口名称在 PascalCase 中。

    ¥A type alias or an interface name are in PascalCase.

  • 类型的成员名称在 camelCase 中。

    ¥Member names of a type are in camelCase.

  • readonly 属性和 getter 名称也可以在 CONSTANT_CASE 中。

    ¥readonly property and getter names can also be in CONSTANT_CASE.

type Named = {
readonly fullName: string;
specialMethod(): void;
};
interface Named {
readonly fullName: string;
specialMethod(): void;
}
interface PersonConstructor {
readonly MAX_FRIEND_COUNT: number;
get SPECIAL_PERSON_INSTANCE(): Person;
new(): Person;
}

错误类型别名的示例:

¥Examples of an incorrect type alias:

type person = { fullName: string };
code-block.ts:1:6 lint/style/useNamingConvention  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This type alias name should be in PascalCase.

> 1 │ type person = { fullName: string };
^^^^^^
2 │

Safe fix: Rename this symbol in PascalCase.

1 - type·person·=·{·fullName:·string·};
1+ type·Person·=·{·fullName:·string·};
2 2

¥Literal object member names

const alice = {
fullName: "Alice",
}

错误名称的示例:

¥Example of an incorrect name:

const alice = {
full_name: "Alice",
}
code-block.js:2:5 lint/style/useNamingConvention ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This object property name should be in camelCase.

1 │ const alice = {
> 2 │ full_name: “Alice”,
^^^^^^^^^
3 │ }
4 │

导入和导出别名和命名空间

Section titled 导入和导出别名和命名空间

¥Import and export aliases and namespaces

导入和导出命名空间在 camelCasePascalCase 中。

¥Import and export namespaces are in camelCase or PascalCase.

import * as myLib from "my-lib";
import * as Framework from "framework";
export * as myLib from "my-lib";
export * as Framework from "framework";

importexport 别名在 camelCasePascalCaseCONSTANT_CASE 中:

¥import and export aliases are in camelCase, PascalCase, or CONSTANT_CASE:

import assert, {
deepStrictEqual as deepEqual,
AssertionError as AssertError
} from "node:assert";

错误名称的示例:

¥Examples of an incorrect name:

import * as MY_LIB from "my-lib";
code-block.ts:1:13 lint/style/useNamingConvention  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This import namespace name should be in camelCase or PascalCase.

> 1 │ import * as MY_LIB from “my-lib”;
^^^^^^
2 │

Safe fix: Rename this symbol in camelCase.

1 - import·*·as·MY_LIB·from·my-lib;
1+ import·*·as·myLib·from·my-lib;
2 2

¥TypeScript type parameter names

TypeScript 类型参数名称在 PascalCase 中。

¥A TypeScript type parameter name is in PascalCase.

function id<Val>(value: Val): Val { /* ... */}

¥TypeScript namespace names

TypeScript namespace 名称在 camelCasePascalCase 中。

¥A TypeScript namespace names are in camelCase or in PascalCase.

namespace mathExtra {
/*...*/
}
namespace MathExtra {
/*...*/
}

¥Ignored declarations

请注意,某些声明始终被忽略。你不能对它们应用约定。这是 eof 的情况:

¥Note that some declarations are always ignored. You cannot apply a convention to them. This is the cas eof:

  • 不是标识符的成员名称

    ¥Member names that are not identifiers

class C {
["not an identifier"]() {}
}
  • 命名导入

    ¥Named imports

import { an_IMPORT } from "mod"
  • 解构对象属性

    ¥destructured object properties

const { destructed_PROP } = obj;
  • 标有 override 的类成员 ==

    ¥class member marked with override

class C extends B {
override overridden_METHOD() {}
}
  • 外部 TypeScript 模块内的声明

    ¥declarations inside an external TypeScript module

declare module "myExternalModule" {
export interface my_INTERFACE {}
}

¥Options

规则提供了几个选项,详见以下小节。

¥The rule provides several options that are detailed in the following subsections.

{
"//": "...",
"options": {
"strictCase": false,
"requireAscii": true,
"enumMemberCase": "CONSTANT_CASE",
"conventions": [
{
"selector": {
"kind": "memberLike",
"modifiers": ["private"]
},
"match": "_(.+)",
"formats": ["camelCase"]
}
]
}
}

当此选项设置为 true 时,它禁止在 camelCasePascalCase 中使用连续的大写字符。例如,当选项设置为 true 时,HTTPServeraHTTPServer 将抛出错误。这些名称应重命名为 HttpServeraHttpServer

¥When this option is set to true, it forbids consecutive uppercase characters in camelCase and PascalCase. For instance, when the option is set to true, HTTPServer or aHTTPServer will throw an error. These names should be renamed to HttpServer and aHttpServer

当选项设置为 false 时,允许连续的大写字符。HTTPServeraHTTPServer 非常有效。

¥When the option is set to false, consecutive uppercase characters are allowed. HTTPServer and aHTTPServer are so valid.

默认:true

¥Default: true

当此选项设置为 true 时,它禁止包含非 ASCII 字符的名称。例如,当选项设置为 true 时,café안녕하세요 将抛出错误。

¥When this option is set to true, it forbids names that include non-ASCII characters. For instance, when the option is set to true, café or 안녕하세요 will throw an error.

当选项设置为 false 时,名称可能包含非 ASCII 字符。café안녕하세요 非常有效。

¥When the option is set to false, names may include non-ASCII characters. café and 안녕하세요 are so valid.

默认:false

¥Default: false

此选项将在 Biome 2.0 中默认启用。

¥This option will be turned on by default in Biome 2.0.

默认情况下,规则强制遵循 TypeScript 编译器团队 后面的命名约定:enum 成员位于 PascalCase 中。

¥By default, the rule enforces the naming convention followed by the TypeScript Compiler team: an enum member is in PascalCase.

你可以通过设置 enumMemberCase 选项来强制执行另一个约定。支持的情况是:PascalCaseCONSTANT_CASEcamelCase

¥You can enforce another convention by setting enumMemberCase option. The supported cases are: PascalCase, CONSTANT_CASE, and camelCase.

此选项将来将被弃用。改用 conventions 选项。

¥This option will be deprecated in the future. Use the conventions option instead.

¥conventions (Since v1.8.0)

conventions 选项允许应用自定义约定。该选项采用一组约定。每个约定都是一个对象,它包含一个可选的 selector 和一个或多个要求(matchformats)。

¥The conventions option allows applying custom conventions. The option takes an array of conventions. Every convention is an object that includes an optional selector and one or more requirements (match and formats).

例如,你可以强制使用 CONSTANT_CASE 进行全局 const 声明:

¥For example, you can enforce the use of CONSTANT_CASE for global const declarations:

{
"//": "...",
"options": {
"conventions": [
{
"selector": {
"kind": "const",
"scope": "global"
},
"formats": ["CONSTANT_CASE"]
}
]
}
}

选择器描述约定适用于哪些声明。你可以根据几个标准选择一个声明:

¥A selector describes which declarations the convention applies to. You can select a declaration based on several criteria:

  • kind:声明的类型如下:

    ¥kind: the kind of the declaration among:

    • any(如果未设置类型,则为默认类型)

      ¥any (default kind if the kind is unset)

    • typeLike:类、枚举、类型别名和接口

      ¥typeLike: classes, enums, type aliases, and interfaces

    • class

    • enum

    • interface

    • typeAlias

    • function:命名函数声明和表达式

      ¥function: named function declarations and expressions

    • namespaceLike:TypeScript 命名空间、导入和导出命名空间 (import * as namespace from)

      ¥namespaceLike: TypeScript namespaces, import and export namespaces (import * as namespace from)

    • namespace:TypeScript 命名空间

      ¥namespace: TypeScript namespaces

    • importNamespace

    • exportNamespace

    • importAlias:默认导入和命名导入的别名

      ¥importAlias: default imports and aliases of named imports

    • exportAlias:重新导出名称的别名

      ¥exportAlias: aliases of re-exported names

    • variable:const、let、using 和 var 声明

      ¥variable: const, let, using, and var declarations

    • const

    • let

    • var

    • using

    • functionParameter

    • catchParameter

    • indexParameter:索引签名的参数

      ¥indexParameter: parameters of index signatures

    • typeParameter:通用类型参数

      ¥typeParameter: generic type parameter

    • classMember:类属性、参数属性、方法、getter 和 setter

      ¥classMember: class properties, parameter properties, methods, getters, and setters

    • classProperty:类属性,包括参数属性

      ¥classProperty: class properties, including parameter properties

    • classMethod

    • classGetter

    • classSetter

    • objectLiteralMember:文字对象属性、方法、getter 和 setter

      ¥objectLiteralMember: literal object properties, methods, getters, and setters

    • objectLiteralProperty

    • objectLiteralMethod

    • objectLiteralGetter

    • objectLiteralSetter

    • typeMember:在类型别名和接口中声明的属性、方法、getter 和 setter

      ¥typeMember: properties, methods, getters, and setters declared in type aliases and interfaces

    • typeProperty

    • typeMethod

    • typeGetter

    • typeSetter

  • modifiers:修饰符数组,其中包括:

    ¥modifiers: an array of modifiers among:

    • abstract:适用于类成员和类

      ¥abstract: applies to class members and classes

    • private:适用于类成员

      ¥private: applies to class members

    • protected:适用于类成员

      ¥protected: applies to class members

    • readonly:适用于类成员和类型成员

      ¥readonly: applies to class members and type members

    • static:适用于类成员

      ¥static: applies to class members

  • scope:声明出现的位置。允许的值:

    ¥scope: where the declaration appears. Allowed values:

    • any:任何地方(如果未设置范围,则为默认值)

      ¥any: anywhere (default value if the scope is unset)

    • global:全局范围(还包括命名空间范围)

      ¥global: the global scope (also includes the namespace scopes)

对于每个声明,都会遍历 conventions 数组,直到选择器选择该声明。约定的要求在声明中得到验证。

¥For each declaration, the conventions array is traversed until a selector selects the declaration. The requirements of the convention are so verified on the declaration.

约定必须至少设置以下一项要求:

¥A convention must set at least one requirement among:

如果同时设置了 matchformats,则根据正则表达式的第一次捕获检查 formats。仅测试第一次捕获。其他捕获被忽略。如果未捕获任何内容,则忽略 formats

¥If both match and formats are set, then formats is checked against the first capture of the regular expression. Only the first capture is tested. Other captures are ignored. If nothing is captured, then formats is ignored.

在下面的例子中,我们检查以下约定:

¥In the following example, we check the following conventions:

  • 私有属性以 _ 开头,至少包含两个字符

    ¥A private property starts with _ and consists of at least two characters

  • 捕获的名称(不带前导 _ 的名称)在 camelCase 中。

    ¥The captured name (the name without the leading _) is in camelCase.

{
// ...
"options": {
"conventions": [
{
"selector": {
"kind": "classMember",
"modifiers": ["private"]
},
"match": "_(.+)",
"formats": ["camelCase"]
}
]
}
}

如果设置了 match 而未设置 formats,则正则表达式捕获的名称部分将转发到数组的下一个约定。在下面的例子中,我们要求私有类成员以 _ 开头,所有类成员都在 [“camelCase”] 中。

¥If match is set and formats is unset, then the part of the name captured by the regular expression is forwarded to the next conventions of the array. In the following example, we require that private class members start with _ and all class members are in [“camelCase”].

{
// ...
"options": {
"conventions": [
{
"selector": {
"kind": "classMember",
"modifiers": ["private"]
},
"match": "_(.+)"
// We don't need to specify `formats` because the capture is forwarded to the next conventions.
},
{
"selector": {
"kind": "classMember"
},
"formats": ["camelCase"]
}
]
}
}

如果未选择声明,或者在没有更多约定的情况下转发捕获,则将根据默认约定验证声明名称。因为默认约定已经确保类成员在 [“camelCase”] 中,所以前面的示例可以简化为:

¥If a declaration is not selected or if a capture is forwarded while there are no more conventions, then the declaration name is verified against the default conventions. Because the default conventions already ensure that class members are in [“camelCase”], the previous example can be simplified to:

{
// ...
"options": {
"conventions": [
{
"selector": {
"kind": "classMember",
"modifiers": ["private"]
},
"match": "_(.+)"
// We don't need to specify `formats` because the capture is forwarded to the next conventions.
}
// default conventions
]
}
}

如果捕获与初始名称相同(它不是初始名称的一部分),则在根据默认约定进行检查之前,会修剪前导和尾随下划线和美元符号。在前面的例子中,捕获是名称的一部分,因为 _ 不包含在捕获中。

¥If the capture is identical to the initial name (it is not a part of the initial name), then, leading and trailing underscore and dollar signs are trimmed before being checked against default conventions. In the previous example, the capture is a part of the name because _ is not included in the capture.

你可以通过在数组末尾添加一个接受任何内容的约定来重置所有默认约定:

¥You can reset all default conventions by adding a convention at the end of the array that accepts anything:

{
// ...
"options": {
"conventions": [
// your conventions
// ...
// Otherwise, accept anything
{
"match": ".*"
}
]
}
}

让我们举一个更复杂的例子,遵循以下约定:

¥Let’s take a more complex example with the following conventions:

  • 接受变量名 ij,并根据下一个约定检查所有其他名称。

    ¥Accept variable names i, j, and check all other names against the next conventions.

  • 所有标识符必须至少包含两个字符。

    ¥All identifiers must contain at least two characters.

  • 我们要求 private 类成员以下划线 _ 开头。

    ¥We require private class members to start with an underscore _.

  • 我们要求 static readonly 类属性在 CONSTANT_CASE 中。private static readonly 属性也必须以下划线开头,如先前的约定所规定。

    ¥We require static readonly class properties to be in CONSTANT_CASE. A private static readonly property must also start with an underscore as dictated by the previous convention.

  • 我们要求全局常量在 CONSTANT_CASE 中,并且我们允许这些常量用双下划线括起来或命名为 _SPECIAL_

    ¥We require global constants to be in CONSTANT_CASE and we allow these constants to be enclosed by double underscores or to be named _SPECIAL_.

  • 我们要求接口以 I 开头,但以 Error 结尾的接口除外,并且要在 PascalCase 中。

    ¥We require interfaces to start with I, except for interfaces ending with Error, and to be in PascalCase.

  • 所有其他名称遵循默认约定

    ¥All other names follow the default conventions

{
// ...
"options": {
"conventions": [
{
"selector": {
"kind": "variable"
},
"match": "[ij]|(.*)"
},
{
"match": "(.{2,})"
},
{
"selector": {
"kind": "classMember",
"modifiers": ["private"]
},
"match": "_(.+)"
}, {
"selector": {
"kind": "classProperty",
"modifiers": ["static", "readonly"]
},
"formats": ["CONSTANT_CASE"]
}, {
"selector": {
"kind": "const",
"scope": "global"
},
"match": "__(.+)__|_SPECIAL_|(.+)",
"formats": ["CONSTANT_CASE"]
}, {
"selector": {
"kind": "interface"
},
"match": "I(.*)|(.*?)Error",
"formats": ["PascalCase"]
}
// default conventions
]
}
}

¥Regular expression syntax

match 选项采用支持以下语法的正则表达式:

¥The match option takes a regular expression that supports the following syntaxes:

  • 贪婪量词 *?+{n}{n,m}{n,}{m}

    ¥Greedy quantifiers *, ?, +, {n}, {n,m}, {n,}, {m}

  • 非贪婪量词 *???+?{n}?{n,m}?{n,}?{m}?

    ¥Non-greedy quantifiers *?, ??, +?, {n}?, {n,m}?, {n,}?, {m}?

  • 任何字符匹配器 .

    ¥Any character matcher .

  • 更改已建立语法的格式。

    ¥Character classes [a-z], [xyz], [^a-z]

  • 替代 |

    ¥Alternations |

  • 捕获组 ()

    ¥Capturing groups ()

  • 非捕获组 (?:)

    ¥Non-capturing groups (?:)

  • 一组有限的转义字符,包括所有特殊字符和常规字符串转义字符 \f\n\r\t\v

    ¥A limited set of escaped characters including all special characters and regular string escape characters \f, \n, \r, \t, \v

¥Related links