Skip to main content
ClaudeWave
EN, English
Skill2k repo starsupdated 7mo ago

coding-standards

This coding standards skill provides comprehensive guidelines for TypeScript, JavaScript, React, and Node.js development, covering principles like readability, KISS, DRY, and YAGNI along with specific best practices for naming conventions, immutability patterns, error handling, type safety, and component structure. Use this when establishing code quality standards for a project, reviewing code, or training developers on consistent development practices across teams.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/xu-xiang/everything-claude-code-zh /tmp/coding-standards && cp -r /tmp/coding-standards/docs/ja-JP/skills/coding-standards ~/.claude/skills/coding-standards
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# 编码标准与最佳实践

适用于所有项目的通用编码标准。

## 代码质量原则

### 1. 可读性优先 (Readability First)

* 代码被阅读的次数远多于编写的次数
* 明确的变量名和函数名
* 优先考虑自描述代码而非注释
* 保持格式一致

### 2. KISS (Keep It Simple, Stupid)

* 采用能运行的最简单方案
* 避免过度设计
* 避免过早优化
* 易于理解 > 巧妙的代码

### 3. DRY (Don't Repeat Yourself)

* 将通用逻辑提取到函数中
* 创建可复用组件
* 在模块间共享工具函数 (Utility functions)
* 避免复制粘贴式编程

### 4. YAGNI (You Aren't Gonna Need It)

* 不要预先构建不需要的功能
* 避免臆测性的泛化
* 仅在必要时增加复杂度
* 从简单开始,按需进行重构 (Refactoring)

## TypeScript/JavaScript 标准

### 变量命名

```typescript
// ✅ 推荐:描述性名称
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000

// ❌ 错误:不明确的名称
const q = 'election'
const flag = true
const x = 1000
```

### 函数命名

```typescript
// ✅ 推荐:动词-名词模式
async function fetchMarketData(marketId: string) { }
function calculateSimilarity(a: number[], b: number[]) { }
function isValidEmail(email: string): boolean { }

// ❌ 错误:不明确或仅使用名词
async function market(id: string) { }
function similarity(a, b) { }
function email(e) { }
```

### 不变性模式 (Immutability Patterns)(重要)

```typescript
// ✅ 始终使用展开运算符 (Spread operator)
const updatedUser = {
  ...user,
  name: 'New Name'
}

const updatedArray = [...items, newItem]

// ❌ 绝不直接修改(Mutate)
user.name = 'New Name'  // 错误
items.push(newItem)     // 错误
```

### 错误处理 (Error Handling)

```typescript
// ✅ 推荐:全面的错误处理
async function fetchData(url: string) {
  try {
    const response = await fetch(url)

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    return await response.json()
  } catch (error) {
    console.error('Fetch failed:', error)
    throw new Error('Failed to fetch data')
  }
}

// ❌ 错误:缺乏错误处理
async function fetchData(url) {
  const response = await fetch(url)
  return response.json()
}
```

### Async/Await 最佳实践

```typescript
// ✅ 推荐:尽可能并行执行
const [users, markets, stats] = await Promise.all([
  fetchUsers(),
  fetchMarkets(),
  fetchStats()
])

// ❌ 错误:非必要的串行执行
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()
```

### 类型安全 (Type Safety)

```typescript
// ✅ 推荐:正确的类型
interface Market {
  id: string
  name: string
  status: 'active' | 'resolved' | 'closed'
  created_at: Date
}

function getMarket(id: string): Promise<Market> {
  // 实现
}

// ❌ 错误:使用 'any'
function getMarket(id: any): Promise<any> {
  // 实现
}
```

## React 最佳实践

### 组件结构

```typescript
// ✅ 推荐:带类型的函数式组件
interface ButtonProps {
  children: React.ReactNode
  onClick: () => void
  disabled?: boolean
  variant?: 'primary' | 'secondary'
}

export function Button({
  children,
  onClick,
  disabled = false,
  variant = 'primary'
}: ButtonProps) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className={`btn btn-${variant}`}
    >
      {children}
    </button>
  )
}

// ❌ 错误:无类型、结构不清晰
export function Button(props) {
  return <button onClick={props.onClick}>{props.children}</button>
}
```

### 自定义钩子 (Custom Hooks)

```typescript
// ✅ 推荐:可复用的自定义钩子
export function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => clearTimeout(handler)
  }, [value, delay])

  return debouncedValue
}

// 用法
const debouncedQuery = useDebounce(searchQuery, 500)
```

### 状态管理 (State Management)

```typescript
// ✅ 推荐:正确的状态更新
const [count, setCount] = useState(0)

// 基于先前状态的函数式更新
setCount(prev => prev + 1)

// ❌ 错误:直接引用状态
setCount(count + 1)  // 在异步场景中可能会过期
```

### 条件渲染 (Conditional Rendering)

```typescript
// ✅ 推荐:清晰的条件渲染
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}

// ❌ 错误:三元运算符地狱
{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}
```

## API 设计标准

### REST API 规范

```
GET    /api/markets              # 列出所有市场
GET    /api/markets/:id          # 获取特定市场
POST   /api/markets              # 创建新市场
PUT    /api/markets/:id          # 更新市场(完整更新)
PATCH  /api/markets/:id          # 更新市场(部分更新)
DELETE /api/markets/:id          # 删除市场

# 用于过滤的查询参数
GET /api/markets?status=active&limit=10&offset=0
```

### 响应格式

```typescript
// ✅ 推荐:一致的响应结构
interface ApiResponse<T> {
  success: boolean
  data?: T
  error?: string
  meta?: {
    total: number
    page: number
    limit: number
  }
}

// 成功响应
return NextResponse.json({
  success: true,
  data: markets,
  meta: { total: 100, page: 1, limit: 10 }
})

// 错误响应
return NextResponse.json({
  success: false,
  error: 'Invalid request'
}, { status: 400 })
```

### 输入验证 (Input Validation)

```typescript
import { z } from 'zod'

// ✅ 推荐:架构验证 (Schema validation)
const CreateMarketSchema = z.object({
  name: z.string().min(1).max(200),
  description: z.string().min(1).max(2000),
  endDate: z.string().datetime(),
  categories: z.array(z.string()).min(1)
})

export async function POST(request: Request) {
  const body = await request.json()

  try {
    const validated = CreateMarketSchema.parse(body)
    // 使用验证后的数据继续
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({
        success: false,
        error: 'Validation failed',
        details: error.errors
      }, { status: 400 })
    }
  }
}
```

## 文件结构

### 项目结构

```
src/
├── app/                    # Next.js App 路由
│   ├── api/               # API 路由
│   ├── markets/           # 市场页面
│   └── (auth)/           # 认证页面(路由组)
├── components/            # React 组件
│   ├── ui/               # 通用 UI 组件
│   ├── forms/            # 表单组件
│   └── layouts/          # 布局组件
├── hooks/                # 自定义 React 钩子
├── lib/                  # 工具类与配置
│   ├── api/             # API 客户端
│   ├── utils/           # 辅助函数
│   └── constants/       # 常量
├── types/                # TypeScript 类型
└── styles/              # 全局样式
```

### 文件命名

```
components/Button.tsx          # 组件使用 PascalCase
hooks/useAuth.ts              # 使用 'use'
api-designSkill

生产级 API 的 REST API 设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和速率限制。

architectSubagent

用于系统设计、可扩展性及技术决策的软件架构专家。在规划新功能、重构大型系统或做出架构决策时请主动(PROACTIVELY)使用。

article-writingSkill

编写文章、指南、博客、教程、时事通讯(Newsletter)等长内容,支持从示例或品牌指南中提取独特的语感语调。适用于需要撰写超过一个段落的精炼文本,尤其是对语气一致性、结构和可信度有较高要求时。

backend-patternsSkill

后端架构模式、API 设计、数据库优化以及 Node.js、Express 和 Next.js API 路由的服务端最佳实践。

build-error-resolverSubagent

构建与 TypeScript 错误修复专家。当构建失败或出现类型错误时,请主动(PROACTIVELY)使用。仅修复构建/类型错误,保持最小差异(diff),不进行架构性修改。重点是快速使构建通过(get the build green)。

chief-of-staffSubagent

个人通讯幕僚 (Chief of Staff),负责分拣电子邮件、Slack、LINE 和 Messenger。将消息分类为 4 个级别 (skip/info_only/meeting_info/action_required),生成草稿回复,并通过钩子 (Hooks) 强制执行发送后的后续跟进。适用于管理多渠道通讯工作流。

clawSlash Command

启动 NanoClaw 智能体 (Agent) REPL — 一个由 claude CLI 驱动的持久化、会话感知 (session-aware) 的 AI 助手。

clickhouse-ioSkill

ClickHouse 数据库模式、查询优化、分析以及高性能分析工作负载的数据工程最佳实践。