Claude Code 完全配置指南:Skills、Agents、Hooks 提升开发效率
Claude Code 完全配置指南:Skills、Agents、Hooks 提升开发效率
Claude Code 是 Anthropic 推出的 AI 编程助手,它不仅能理解代码库、执行任务、调试问题,更重要的是:它高度可配置。
通过合理配置 settings.local.json、Skills、Agents、Commands 和 Hooks,你可以将 Claude Code 从一个通用助手打造成专属于你团队的超级开发伙伴。
本文涵盖:
- 配置系统架构(settings.json 层级)
- Skills:让 Claude 学会你的项目规范
- Agents:专业化分工的子智能体
- Commands:快捷命令提升效率
- Hooks:自动化工作流
- 实战案例:10x 开发效率的配置技巧
配置系统架构
Claude Code 的配置遵循层级继承原则:
1. Global Settings
~/.claude/settings.json # 全局默认配置
~/.claude/settings.local.json # 全局个人配置(gitignore)
2. Project Settings
./.claude/settings.json # 项目默认配置
./.claude/settings.local.json # 项目个人配置(gitignore)
3. Plugin Settings
plugins/my-plugin/.claude-plugin/plugin.json优先级:Project Local > Project Default > Global Local > Global Default
快速开始:创建项目配置
# 在项目根目录创建配置目录
mkdir -p .claude
# 创建项目配置文件
cat > .claude/settings.local.json << 'EOF'
{
"instructions": "You are working on a Next.js project with TypeScript.",
"skills": ["./.claude/skills"],
"agents": ["./.claude/agents"],
"commands": ["./.claude/commands"]
}
EOFSkills:让 Claude 学会你的项目规范
Skills 是可复用的知识模块,通过 SKILL.md 文件定义。Claude 会在需要时按需加载相关知识,而不是塞满 system prompt。
Skill 结构
.claude/skills/my-skill/
├── SKILL.md # 技能定义(必需)
├── references/ # 参考文档(可选)
└── scripts/ # 伴随脚本(可选)SKILL.md 格式
---
name: react-best-practices
description: Use this for React development tasks to ensure code follows team standards
---
# React Best Practices
## Component Structure
- Use functional components with hooks
- Keep components under 200 lines
- Extract reusable logic into custom hooks
## State Management
- Use useState for local state
- Use Zustand for global state
- Avoid prop drilling with context
## Example
\```tsx
// ✅ Good: Custom hook for logic
function useUserData() {
const [user, setUser] = useState(null);
// ...
return { user, setUser };
}
// ❌ Bad: Logic mixed with UI
function UserProfile() {
const [user, setUser] = useState(null);
// 20 lines of data fetching logic...
return {user.name};
}
\```实用 Skills 示例
1. 项目约定 Skill
.claude/skills/project-conventions/SKILL.md:
---
name: project-conventions
description: Project-specific coding standards and conventions
---
# Project Conventions
## File Naming
- Components: PascalCase (UserProfile.tsx)
- Utilities: camelCase with util prefix (formatDate.ts)
- Hooks: camelCase with use prefix (useUserData.ts)
- Tests: PascalCase with .test suffix (UserProfile.test.ts)
## Import Order
1. React imports
2. Third-party libraries
3. Internal components
4. Relative imports
5. CSS imports
## API Patterns
- All API calls go through `/src/lib/api/`
- Use async/await, not promises
- Error handling with try-catch
## Git Conventional
- feat: new feature
- fix: bug fix
- docs: documentation
- refactor: code refactoring2. 技术栈参考 Skill
.claude/skills/tech-stack/SKILL.md:
---
name: tech-stack
description: Technical stack reference and usage patterns
---
# Tech Stack Reference
## Framework: Next.js 14
- Use App Router (not Pages Router)
- Server Components by default
- Client Components only when needed (useState, useEffect)
## Database: Prisma
- Schema: `prisma/schema.prisma`
- Migrations: `npx prisma migrate dev`
- Client: `@prisma/client`
## Styling: Tailwind CSS
- Use utility classes
- Custom components in `@/components/ui/*`
- Dark mode: `dark:` prefix
## Deployment: Vercel
- Auto-deploy on push to main
- Preview deployments for PRs
- Environment variables in Vercel dashboardSkill 触发时机
Claude 会自动检测何时需要加载 Skill:
# Claude 内部逻辑(伪代码)
if task_matches_skill_trigger(task, available_skills):
skill_content = load_skill(skill_name)
inject_into_context(skill_content)你也可以明确请求:
> Load the react-best-practices skill and review this componentAgents:专业化分工的子智能体
Agents 是专门的子智能体,每个 Agent 有特定的职责和上下文。它们通过异步 mailbox 通信,可以并行工作。
Agent 定义
.claude/agents/security-reviewer.md:
---
name: security-reviewer
description: Reviews code for security vulnerabilities and best practices
---
# Security Reviewer Agent
You are a security specialist. Your role is to:
1. **Check for common vulnerabilities**:
- SQL injection
- XSS (cross-site scripting)
- CSRF (cross-site request forgery)
- Authentication/authorization issues
- Sensitive data exposure
2. **Review dependencies**:
- Outdated packages with known CVEs
- Unnecessary dependencies
3. **Enforce security practices**:
- Input validation
- Output encoding
- Parameterized queries
- Secure headers
## Output Format
For each file reviewed, provide:
```markdown
## Security Review: [filename]
### Critical Issues
- [ ] Issue description
- Severity: HIGH
- Recommendation: Fix immediately
### Medium Issues
- [ ] Issue description
- Severity: MEDIUM
- Recommendation: Fix soon
### Low Issues
- [ ] Issue description
- Severity: LOW
- Recommendation: Nice to have
### Summary
- Total issues: X critical, Y medium, Z low
- Overall security score: 7/10Agent 团队协作
场景:代码提交前的完整审查流程
# 主 Agent 协调
> review this PR with the security and performance agents
# 主 Agent 分配任务:
# 1. 安全审查 → security-reviewer agent
# 2. 性能分析 → performance-analyst agent
# 3. 测试覆盖 → test-coverage agent
# 各 Agent 并行工作,异步汇报结果Agent Mailbox 通信协议:
// .claude/mailboxes/security-reviewer.jsonl
{"type": "request", "from": "main", "task": "Review auth.ts for vulnerabilities", "timestamp": "2026-03-30T10:00:00Z"}
// Agent 处理并回复
{"type": "response", "from": "security-reviewer", "status": "completed", "issues": [...], "timestamp": "2026-03-30T10:02:30Z"}实用 Agents 示例
性能分析 Agent
.claude/agents/performance-analyst.md:
---
name: performance-analyst
description: Analyzes code for performance bottlenecks and optimization opportunities
---
# Performance Analyst Agent
Analyze code for:
1. **Runtime Performance**:
- O(n²) or worse algorithms
- Unnecessary re-renders (React)
- Memory leaks
- Blocking operations
2. **Bundle Size**:
- Large dependencies
- Unused imports
- Tree-shaking opportunities
3. **Database Performance**:
- N+1 queries
- Missing indexes
- Unoptimized joins
## Tools
- React DevTools Profiler
- Lighthouse CI
- Bundle Analyzer测试生成 Agent
.claude/agents/test-generator.md:
---
name: test-generator
description: Generates comprehensive unit and integration tests
---
# Test Generator Agent
Generate tests that:
1. **Cover happy paths**
2. **Test edge cases**
3. **Validate error handling**
4. **Mock external dependencies**
## Testing Framework
- Unit tests: Vitest
- Integration tests: Playwright
- Coverage target: 80%
## Example Output
\```typescript
describe('UserService', () => {
it('should create user with valid data', async () => {
const user = await userService.create({
email: 'test@example.com',
password: 'SecurePass123!'
});
expect(user.id).toBeDefined();
});
it('should reject duplicate email', async () => {
await expect(
userService.create({ email: 'existing@example.com' })
).rejects.toThrow('Email already exists');
});
});
\```Commands:快捷命令提升效率
Commands 是可复用的任务模板,通过 /command-name 快速调用。
Command 定义
.claude/commands/review.md:
---
description: Review code changes following project standards
---
# Code Review
Review the following changes:
1. Check adherence to coding standards
2. Identify potential bugs
3. Suggest optimizations
4. Verify test coverage
## Context
- Branch: {{git_branch}}
- Files changed: {{git_diff_stat}}命令中使用变量
Claude Code 支持动态变量注入:
## Context
- Current file: {{current_file}}
- Git branch: {{git_branch}}
- Recent commits: {{git_log}}
- User input: {{user_input}}实用 Commands 示例
1. 快速修复 Command
.claude/commands/fix.md:
---
description: Fix the current error or issue
---
# Fix Mode
Analyze the current file/directory and:
1. Identify errors (TS, ESLint, runtime)
2. Propose fixes
3. Apply fixes after confirmation
## Focus
{{current_file}}
## Checklist
- [ ] Type errors resolved
- [ ] Linting errors resolved
- [ ] Tests passing
- [ ] No breaking changes2. 重构建议 Command
.claude/commands/refactor.md:
---
description: Suggest refactoring opportunities
---
# Refactoring Suggestions
Analyze {{current_file}} for:
1. Code smells (long functions, duplicated code)
2. Design pattern opportunities
3. Performance optimizations
4. Type safety improvements
## Output Format
```markdown
## Refactoring Opportunities
### High Priority
1. [Code smell]
- Location: line X
- Suggestion: [Improvement]
- Impact: [Benefits]
### Medium Priority
...
#### 3. 文档生成 Command
**`.claude/commands/docs.md`**:
```markdown
---
description: Generate documentation for code
---
# Documentation Generator
Generate comprehensive docs for {{current_file}}:
1. JSDoc comments for functions
2. README if module entry point
3. Usage examples
4. Type definitions if TypeScript
## Style
- Clear, concise descriptions
- Code examples for all public APIs
- TypeScript types in backticksHooks:自动化工作流
Hooks 在特定事件时自动触发,用于强制规则、自动化任务、集成工具。
Hook 事件类型
| 事件 | 触发时机 | 用途 |
|---|---|---|
SessionStart |
会话开始 | 加载项目上下文 |
PreToolUse |
工具调用前 | 验证操作安全性 |
PostToolUse |
工具调用后 | 自动格式化、lint |
Stop |
任务完成 | 生成报告、清理 |
Hook 配置
.claude/hooks.json:
{
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "git status",
"timeout": 5
},
{
"type": "prompt",
"prompt": "Load project-conventions skill and review recent git history"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "npx prettier --write $CLAUDE_FILE_PATH",
"timeout": 10
},
{
"type": "command",
"command": "npx eslint --fix $CLAUDE_FILE_PATH",
"timeout": 15
}
]
}
],
"PreToolUse": [
{
"matcher": "bash.*rm|-rf|delete",
"hooks": [
{
"type": "prompt",
"prompt": "CRITICAL: About to delete files. Verify this is intentional and user has approved."
}
]
}
]
}Hook 类型
1. Prompt Hook
在关键时刻注入提示:
{
"PreToolUse": [
{
"matcher": "Write.*package.json",
"hooks": [
{
"type": "prompt",
"prompt": "Verify all new dependencies are necessary and securely versioned. No '*' ranges."
}
]
}
]
}2. Command Hook
自动执行命令:
{
"PostToolUse": [
{
"matcher": "Write.*\\.ts$",
"hooks": [
{
"type": "command",
"command": "npx tsc --noEmit $CLAUDE_FILE_PATH",
"timeout": 30
}
]
}
]
}3. Composite Hook
组合多个操作:
{
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "git diff --stat",
"timeout": 5
},
{
"type": "prompt",
"prompt": "Summarize changes and suggest commit message following conventional commits format"
}
]
}
]
}实用 Hooks 示例
自动化测试 Hook
{
"PostToolUse": [
{
"matcher": "Write.*\\.test\\.(ts|js)$",
"hooks": [
{
"type": "command",
"command": "npm test -- $CLAUDE_FILE_PATH",
"timeout": 60
}
]
}
]
}安全检查 Hook
{
"PreToolUse": [
{
"matcher": "bash.*curl|wget|http",
"hooks": [
{
"type": "prompt",
"prompt": "Security check: Verify URL is trusted and no sensitive data in command"
}
]
}
]
}Git 提交 Hook
{
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Generate conventional commit message based on changes and ask if user wants to commit now"
}
]
}
]
}完整配置示例
项目结构
my-project/
├── .claude/
│ ├── settings.local.json # 项目配置
│ ├── hooks.json # 全局 hooks
│ ├── skills/ # 项目技能
│ │ ├── project-conventions/
│ │ ├── tech-stack/
│ │ └── api-patterns/
│ ├── agents/ # 专业化 agents
│ │ ├── security-reviewer.md
│ │ ├── performance-analyst.md
│ │ └── test-generator.md
│ └── commands/ # 快捷命令
│ ├── review.md
│ ├── fix.md
│ └── docs.mdsettings.local.json
{
"instructions": "You are working on a Next.js 14 e-commerce app with TypeScript, Prisma, and Tailwind CSS.",
"skills": [
"./.claude/skills/project-conventions",
"./.claude/skills/tech-stack",
"./.claude/skills/api-patterns"
],
"agents": [
"./.claude/agents/security-reviewer.md",
"./.claude/agents/performance-analyst.md",
"./.claude/agents/test-generator.md"
],
"commands": [
"./.claude/commands/review.md",
"./.claude/commands/fix.md",
"./.claude/commands/refactor.md"
],
"hooks": "./.claude/hooks.json",
"environment": {
"NODE_ENV": "development",
"DATABASE_URL": "postgresql://localhost:5432/myapp"
},
"allowedPaths": [
"./src",
"./tests",
"./prisma"
],
"deniedPaths": [
"node_modules",
".next",
"dist",
".git"
],
"permissions": {
"allowWrite": true,
"allowBash": true,
"allowNetwork": true,
"confirmDestructive": true
}
}实战案例:10x 开发效率的配置技巧
案例 1:新功能开发工作流
目标:从需求到部署的自动化流程
.claude/commands/feature.md:
---
description: Complete feature development workflow
---
# Feature Development Workflow
## Step 1: Planning
- Create feature branch
- Break down into tasks
- Estimate complexity
## Step 2: Implementation
- Load tech-stack skill
- Generate component boilerplate
- Implement with project-conventions
## Step 3: Testing
- Load test-generator agent
- Generate unit tests
- Generate integration tests
- Run tests and fix failures
## Step 4: Review
- Load security-reviewer agent
- Load performance-analyst agent
- Address all issues
## Step 5: Documentation
- Generate JSDoc
- Update README
- Create changelog entry
## Step 6: Deploy
- Run build
- Create PR
- Request review使用:
> /feature Implement user authentication with OAuth案例 2:Bug 修复工作流
.claude/commands/debug.md:
---
description: Systematic debugging workflow
---
# Debugging Workflow
## 1. Understand the Problem
- Read error messages
- Reproduce the issue
- Check logs
## 2. Identify Root Cause
- Load relevant code
- Use /fix to auto-fix
- Verify fix locally
## 3. Add Regression Test
- Load test-generator agent
- Create test that catches this bug
- Ensure test passes
## 4. Document
- Add inline comments
- Update documentation if needed案例 3:代码质量门禁
.claude/hooks.json:
{
"PostToolUse": [
{
"matcher": "Write.*\\.tsx?$",
"hooks": [
{
"type": "command",
"command": "npx prettier --check $CLAUDE_FILE_PATH",
"timeout": 10
},
{
"type": "command",
"command": "npx eslint $CLAUDE_FILE_PATH",
"timeout": 15
},
{
"type": "command",
"command": "npx tsc --noEmit",
"timeout": 30
}
]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Run all quality checks: formatting, linting, type checking, and tests. Report any failures."
}
]
}
]
}案例 4:团队知识库 Skill
.claude/skills/team-knowledge/SKILL.md:
---
name: team-knowledge
description: Access team's collective knowledge and best practices
---
# Team Knowledge Base
## Architecture Decisions
- Why we chose Next.js over CRA
- Why Prisma over TypeORM
- Why Zustand over Redux
## Common Patterns
- Authentication flow
- Error handling strategy
- API response format
## Gotchas
- Vercel deployment requires environment variables set in dashboard
- Prisma migrations need manual approval in prod
- Tailwind `@apply` directive causes purging issues
## References
- Architecture ADRs: `/docs/architecture/`
- API docs: `/docs/api/`
- Runbooks: `/docs/runbooks/`案例 5:持续集成 Hook
.claude/hooks.json(CI/CD 集成):
{
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "npm run build",
"timeout": 120
},
{
"type": "prompt",
"prompt": "Build complete. Run tests and if all pass, ask if user wants to create a PR to main branch."
}
]
}
]
}进阶技巧
1. 环境变量管理
{
"environment": {
"production": {
"API_URL": "https://api.example.com",
"NODE_ENV": "production"
},
"development": {
"API_URL": "http://localhost:3000",
"NODE_ENV": "development"
}
}
}2. 路径权限控制
{
"allowedPaths": ["./src", "./tests"],
"deniedPaths": ["node_modules", ".next", "dist"],
"permissions": {
"allowWrite": true,
"confirmDestructive": ["rm", "delete", "truncate"]
}
}3. 条件 Hooks
根据分支/文件类型触发不同 hooks:
{
"PostToolUse": [
{
"matcher": "Write.*\\.test\\.",
"condition": "{{git_branch}} == 'main'",
"hooks": [
{
"type": "prompt",
"prompt": "On main branch - ensure tests are comprehensive before committing"
}
]
}
]
}最佳实践
✅ DO
- 按需加载知识:用 Skills 而不是塞满 instructions
- 专业化 Agents:每个 Agent 一个职责
- 渐进式 Hooks:从简单开始,逐步自动化
- 版本控制配置:提交
.claude/settings.json,忽略.local文件 - 团队共享:将通用 Skills/Agents 放入团队仓库
❌ DON'T
- 过度配置:不要把一切自动化,保留人工审查
- 忽略安全:Hooks 验证危险操作
- 硬编码路径:使用环境变量和相对路径
- 混淆配置:保持配置清晰、有注释
- 忽略性能:设置合理的 hook timeout
资源与参考
官方文档
- Claude Code Settings - 完整配置参考
- Extend Claude with Skills - Skills 开发指南
- Automate with Hooks - Hooks 完整指南
- Claude Code Plugins - Plugin 开发
社区资源
- feiskyer/claude-code-settings - 精选配置集合
- VoltAgent/awesome-claude-code-subagents - 100+ Agents 收藏
- lst97/claude-code-sub-agents - 专业化 Agents
文章教程
- Complete Customization Guide - 全面自定义指南
- Beginner's Guide to Claude Code - 初学者完整指南
总结
Claude Code 的真正威力在于其可配置性。通过合理使用:
- Skills - 注入项目知识,让 Claude 理解你的代码库
- Agents - 专业化分工,并行处理复杂任务
- Commands - 快捷命令,一键执行常见工作流
- Hooks - 自动化重复任务,强制团队规范
你可以将 Claude Code 从通用助手打造成团队专属的超级开发者。
开始建议:
- 从简单的 Skills 开始(项目约定)
- 添加 1-2 个常用 Commands(review, fix)
- 配置基础的 Hooks(自动格式化)
- 根据团队需求逐步扩展 Agents 和高级 Hooks
记住:配置的目标是提升效率,而不是增加复杂度。保持简单,逐步迭代。
下一步行动:
- 创建
.claude/settings.local.json - 编写第一个 Skill(项目约定)
- 配置常用 Commands
- 设置自动化 Hooks
- 根据团队反馈持续优化
Happy Coding with Claude! 🚀