命名规范
统一的命名规范能够提高代码可读性,降低团队协作成本。
文件与目录命名
| 类型 | 规范 | 示例 | 说明 | 原因 |
|---|---|---|---|---|
| 业务模块目录 | kebab-case | user-center, purchase-order | - | 保持 URL 友好,且跨操作系统兼容性最好 |
| 组件目录 | PascalCase | UserCard, SubmitButton | - | 与组件名保持一致,便于查找 |
| 组件文件 | PascalCase 或 index.tsx | UserCard.tsx, UserCard/index.tsx | 无样式可用单文件;有样式必须用文件夹+index | 1. 保持组件与样式就近 2. 避免目录文件过多 3. 便于拆分子组件 |
| 样式文件 | index.module.css | UserCard/index.module.css | 必须在组件文件夹内 例外:公共样式( global.css)、UI覆盖(X.overrides.css) | 1. 文件夹名已表明身份 2. 避免重命名时同步修改文件名 |
| Hooks 文件 | camelCase | useAuth.ts, useRequest.ts | 以 use 开头 | React 官方约定,工具链(如 ESLint)依赖此前缀 |
| 逻辑/工具文件 | camelCase | controller.ts, api.ts, dateUtils.ts | 普通 JS/TS 文件 | JS 社区标准惯例 |
| 资源文件 | kebab-case | logo-white.svg, bg-image.png | 静态资源统一小写 | 避免不同操作系统的大小写敏感性问题(如 Windows/Linux) |
代码标识符命名
| 类型 | 规范 | 示例 |
|---|---|---|
| React 组件 | PascalCase | function UserCard() {} |
| 变量 / 函数 | camelCase | const userInfo, function getUser() |
| 常量 | UPPER_SNAKE_CASE | const MAX_COUNT = 10 |
| 类型 / 接口 | PascalCase | interface UserProfile |
| 枚举 | PascalCase | enum UserRole |
布尔值命名
布尔变量/函数应该使用 is、has、can、should 等前缀。
事件处理函数命名
使用 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 {} # 不要用完整单词