Skip to content

命名规范

统一的命名规范能够提高代码可读性,降低团队协作成本。

文件与目录命名

类型规范示例说明原因
业务模块目录kebab-caseuser-center, purchase-order-保持 URL 友好,且跨操作系统兼容性最好
组件目录PascalCaseUserCard, SubmitButton-与组件名保持一致,便于查找
组件文件PascalCaseindex.tsxUserCard.tsx, UserCard/index.tsx无样式可用单文件;有样式必须用文件夹+index1. 保持组件与样式就近
2. 避免目录文件过多
3. 便于拆分子组件
样式文件index.module.cssUserCard/index.module.css必须在组件文件夹内
例外:公共样式(global.css)、UI覆盖(X.overrides.css)
1. 文件夹名已表明身份
2. 避免重命名时同步修改文件名
Hooks 文件camelCaseuseAuth.ts, useRequest.tsuse 开头React 官方约定,工具链(如 ESLint)依赖此前缀
逻辑/工具文件camelCasecontroller.ts, api.ts, dateUtils.ts普通 JS/TS 文件JS 社区标准惯例
资源文件kebab-caselogo-white.svg, bg-image.png静态资源统一小写避免不同操作系统的大小写敏感性问题(如 Windows/Linux)

代码标识符命名

类型规范示例
React 组件PascalCasefunction UserCard() {}
变量 / 函数camelCaseconst userInfo, function getUser()
常量UPPER_SNAKE_CASEconst MAX_COUNT = 10
类型 / 接口PascalCaseinterface UserProfile
枚举PascalCaseenum UserRole

布尔值命名

布尔变量/函数应该使用 ishascanshould 等前缀。

事件处理函数命名

使用 handle 前缀 + 动词。

语义化命名

1. 使用有意义的名称

typescript
✅ 正确
const userList = []
const totalAmount = 0
function calculateTotalPrice() {}

❌ 错误
const list = []               # 太泛化
const total = 0               # 不明确
function calc() {}            # 缩写不清晰

2. 避免无意义的缩写

typescript
✅ 正确
const userInfo = {}
const productList = []
const orderDetail = {}

❌ 错误
const usrInfo = {}            # 不要省略元音
const prodList = []           # 不要随意缩写
const ordDtl = {}             # 不要过度缩写

例外: 业界通用的缩写可以使用。

typescript
✅ 可接受的缩写
const id = '123'              # identifier
const url = 'https://...'     # uniform resource locator
const html = '<div></div>'    # hypertext markup language
const api = {}                # application programming interface
const btn = {}                # button(仅在 CSS 类名中)

3. 使用复数形式表示集合

typescript
✅ 正确
const users = []
const orders = []
const products = []

❌ 错误
const userList = []           # 冗余的 List 后缀
const orderArray = []         # 冗余的 Array 后缀

例外: 当需要区分单个对象和集合时。

typescript
const user = { id: '1' }
const userList = [user]       # 此时 List 后缀有意义

特殊场景

1. 私有变量/函数

使用 _ 前缀表示私有(约定,非强制)。

typescript
class UserService {
  private _cache = new Map()

  private _validateUser(user: User) {
    // ...
  }
}

2. 临时变量

循环中的临时变量可以使用单字母。

typescript
✅ 正确
for (let i = 0; i < 10; i++) {}
users.map((user, index) => {})
Object.entries(obj).forEach(([key, value]) => {})

❌ 错误
for (let index = 0; index < 10; index++) {}  # 过于冗长

3. 泛型参数

使用单个大写字母或 T 开头的 PascalCase

typescript
✅ 正确
function identity<T>(arg: T): T {}
function map<TInput, TOutput>(fn: (input: TInput) => TOutput) {}

❌ 错误
function identity<Type>(arg: Type): Type {}  # 不要用完整单词

Released under the MIT License.