关于 coding-rules
coding-rules 是面向开发者的项目通用编码规范技能,涵盖 TypeScript 与 React/Next.js。内容从类型和导入规则延伸到错误处理及 Git 提交约定。
主要功能
- 01类型定义与空值处理
- 02导入顺序与命名规则
- 03单一职责函数与提前返回
- 04错误处理与注释规范
- 05React/Next.js 组件指引
- 06Conventional Commits 约定
适用场景
- 01统一项目内的编码规范
- 02检查 TypeScript 命名和类型
- 03组织 React/Next.js 组件
- 04编写一致的 Git 提交信息
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ kimny1143/ claude-code-template --skill coding-rules安装后在 Claude Code 中输入/coding-rules确认已加载。
详细介绍
coding-rules - 编码规范
项目通用的编码规则。
1. TypeScript
类型定义
// ✅ 明示的な型定義
interface User {
id: string;
email: string;
name: string;
createdAt: Date;
}
// ✅ 型推論が明確な場合は省略OK
const users = await repository.findAll(); // 戻り値の型は関数から推論
// ❌ any は使わない
const data: any = response.json();
// ✅ unknown を使って安全に処理
const data: unknown = await response.json();
if (isUser(data)) {
console.log(data.email);
}
空值/未定义
// ✅ Optional chaining
const email = user?.profile?.email;
// ✅ Nullish coalescing
const name = user.name ?? 'Anonymous';
// ❌ 非推奨
const name = user.name || 'Anonymous'; // 空文字もfalsy
2. 导入顺序
// 1. 外部ライブラリ
import { useState } from 'react';
import { z } from 'zod';
// 2. 内部モジュール(エイリアス)
import { db } from '@/db';
import { User } from '@/types';
// 3. 相対インポート
import { helper } from './utils';
import styles from './styles.module.css';
3. 命名规范
| 类型 | 规则 | 示例 |
|---|---|---|
| 变量、函数 | camelCase | getUserById, isActive |
| 常量 | UPPER_SNAKE_CASE | MAX_RETRY_COUNT |
| 类、类型 | PascalCase | UserService, CreateUserInput |
| 文件 | kebab-case | user-service.ts |
| React 组件 | PascalCase | UserCard.tsx |
| 环境变量 | UPPER_SNAKE_CASE | DATABASE_URL |
布尔值命名
// ✅ is/has/can/should プレフィックス
const isActive = true;
const hasPermission = user.role === 'admin';
const canEdit = isOwner || isAdmin;
const shouldRefetch = isStale && !isLoading;
4. 函数
单一职责
// ❌ 複数の責任
async function processUser(userId: string) {
const user = await db.select().from(users).where(eq(users.id, userId));
await sendEmail(user.email);
await updateLastLogin(userId);
return user;
}
// ✅ 分割
async function getUser(userId: string) {
return db.select().from(users).where(eq(users.id, userId));
}
async function notifyUser(email: string) {
await sendEmail(email);
}
async function recordLogin(userId: string) {
await updateLastLogin(userId);
}
尽早返回
// ❌ ネスト深い
function processData(data: Data | null) {
if (data) {
if (data.isValid) {
if (data.items.length > 0) {
return data.items.map(process);
}
}
}
return [];
}
// ✅ 早期リターン
function processData(data: Data | null) {
if (!data) return [];
if (!data.isValid) return [];
if (data.items.length === 0) return [];
return data.items.map(process);
}
5. 错误处理
// ✅ カスタムエラークラス
class ValidationError extends Error {
constructor(
message: string,
public field: string
) {
super(message);
this.name = 'ValidationError';
}
}
// ✅ 適切なエラー処理
try {
await riskyOperation();
} catch (error) {
if (error instanceof ValidationError) {
return apiError(error.message, { status: 400 });
}
console.error('Unexpected error:', error);
return apiError('Internal error', { status: 500 });
}
6. 注释
// ✅ WHYを説明
// Stripe APIの制限により、100件ずつバッチ処理する必要がある
const BATCH_SIZE = 100;
// ❌ WHATを説明(コードを読めばわかる)
// ユーザーを取得する
const user = await getUser(id);
// ✅ TODO/FIXME は issue番号付き
// TODO(#123): キャッシュ実装後に削除
// FIXME(#456): 競合状態の対応が必要
7. React/Next.js
服务端组件与客户端组件
// Server Component (デフォルト)
// - データフェッチ
// - 機密情報アクセス
// - バンドルサイズ削減
// Client Component ('use client')
// - useState, useEffect
// - イベントハンドラ
// - ブラウザAPI
// ✅ 最小限のクライアントコンポーネント
'use client';
export function LikeButton({ postId }: { postId: string }) {
const [liked, setLiked] = useState(false);
return <button onClick={() => setLiked(!liked)}>Like</button>;
}
Props
// ✅ 型定義
interface UserCardProps {
user: User;
onEdit?: (id: string) => void;
className?: string;
}
export function UserCard({ user, onEdit, className }: UserCardProps) {
// ...
}
8. Git 提交
Conventional Commits
feat: 新機能追加
fix: バグ修正
docs: ドキュメント
refactor: リファクタリング
test: テスト
chore: その他
示例
feat: add user authentication
fix: resolve login redirect loop
docs: update API documentation
refactor: extract validation logic to separate module
test: add unit tests for UserService
chore: update dependencies
评论
支持 Markdown