團隊協作最佳實踐
在軟體開發領域,團隊協作的效率往往決定了專案的成敗。Claude Code作為一款強大的AI程式設計助手,不僅能提升個人開發效率,更能在團隊協作中發揮巨大價值。本文將深入探討如何在團隊環境中高效使用Claude Code,建立標準化的協作流程,讓AI成為團隊的生產力倍增器。
團隊協作的新正規化
傳統團隊協作的挑戰
常見痛點:
- 知識孤島: 每個開發者熟悉的部分有限,跨模組協作困難
- 程式碼風格不一: 即使有規範,也難以保證100%執行
- 審查效率低: 程式碼審查消耗大量時間,且質量參差不齊
- 新人上手慢: 需要數週才能理解專案架構和編碼規範
- 文件維護難: 程式碼更新快,文件往往跟不上
- 溝通成本高: 簡單問題需要多次會議才能解決
實際案例對比:
傳統協作流程:
新功能开发 (5人团队)
├─ 需求讨论会议: 1小时
├─ 架构设计评审: 1小时
├─ 编码实现 (每人独立): 2天
├─ 代码审查 (2轮): 4小时
├─ 修复审查意见: 0.5天
├─ 集成测试修复: 0.5天
└─ 总计: 约3.5个工作日 + 5小时会议
使用Claude Code最佳化後:
新功能开发 (5人团队 + Claude Code)
├─ 需求讨论 + 快速原型: 30分钟
├─ 架构设计验证 (AI辅助): 30分钟
├─ 编码实现 (AI辅助): 1天
├─ 自动化代码检查 (AI): 即时
├─ 代码审查 (AI辅助): 1小时
├─ 修复建议 (AI辅助): 即时
├─ 集成测试 (AI生成): 自动通过
└─ 总计: 约1.5个工作日 + 1小时会议
效率提升: 57% 的時間節省
Claude Code的團隊價值
核心優勢:
-
知識共享加速器
- CLAUDE.md作為團隊知識的集中儲存
- 新人快速瞭解專案規範,上手時間從2周縮短到2天
- 減少重複問答,每個人都可訪問完整的專案知識
-
程式碼質量守門員
- 實時程式碼規範檢查,不符合規範的程式碼在編寫時就被糾正
- 自動化程式碼審查,捕捉90%以上的常見問題
- 統一程式碼風格,消除"個人風格"差異
-
協作效率倍增器
- 並行處理多項任務,如測試、lint、文件生成
- 自動生成標準化的commit message和PR描述
- 快速程式碼搜尋和依賴分析,節省跨模組理解時間
-
持續學習夥伴
- 團隊共享最佳實踐和最佳化技巧
- 自動記錄常見問題和解決方案
- 累積團隊特有的程式設計模式和工具鏈使用經驗
配置共享與標準化
統一CLAUDE.md配置
團隊協作的第一步是建立標準化的CLAUDE.md配置檔案。這是團隊知識的核心載體。
團隊級CLAUDE.md模板
# Team CLAUDE.md Standard
## Project Metadata
**Project Name:** [项目名称]
**Tech Lead:** [负责人]
**Last Updated:** [更新日期]
**Version:** [配置版本]
## Quick Overview
- **Type:** [Web/Mobile/Desktop/API]
- **Framework:** [主框架]
- **Language:** [TypeScript/JavaScript/Python/etc]
- **Team Size:** [团队人数]
## Technology Stack
### Frontend
- Framework: [React/Vue/Angular]
- State Management: [Redux/Zustand/Pinia]
- Styling: [Tailwind/CSS Modules/Styled Components]
- Build Tool: [Vite/Webpack]
### Backend
- Runtime: [Node.js/Python/Go]
- Framework: [Express/FastAPI/Gin]
- Database: [PostgreSQL/MongoDB/Redis]
- ORM: [Prisma/TypeORM/SQLAlchemy]
### Development Tools
- Package Manager: [npm/pnpm/yarn]
- Testing: [Jest/Vitest/Pytest]
- Linting: [ESLint/Pylint]
- CI/CD: [GitHub Actions/GitLab CI]
## Code Standards
### File Naming
- Components: PascalCase (UserProfile.tsx)
- Utilities: camelCase (formatDate.ts)
- Constants: UPPER_SNAKE_CASE (API_BASE_URL.ts)
- Tests: *.test.ts / *.spec.ts
### Directory Structure
src/ ├── components/ # Reusable UI components ├── pages/ # Page-level components ├── hooks/ # Custom React hooks ├── services/ # API services ├── utils/ # Utility functions ├── types/ # TypeScript type definitions ├── constants/ # Application constants └── tests/ # Test files
### Coding Conventions
1. Use TypeScript strict mode
2. No `any` types allowed
3. All functions must have return types
4. Use const over let
5. Prefer functional components
6. File size max: 300 lines
7. Function length max: 50 lines
8. Cyclomatic complexity max: 10
### Git Workflow
- Branch strategy: GitFlow / Trunk-Based
- Commit message format: Conventional Commits
- PR template required
- Minimum 1 approval required
- CI must pass before merge
## Common Commands
### Development
```bash
npm run dev # Start development server
npm run build # Production build
npm run lint # Run linter
npm run type-check # TypeScript check
npm run test # Run tests
npm run test:watch # Watch mode
npm run test:coverage # Coverage report
Git
git checkout -b feature/XXX # Create feature branch
git checkout -b fix/XXX # Create fix branch
git push origin XXX # Push branch
Task Patterns
When I say "create feature [name]"
- Create feature branch
- Follow feature template in .github/FEATURE_TEMPLATE.md
- Create files: component, hooks, types, tests
- Run tests and linting
- Ask for commit confirmation
When I say "fix bug [description]"
- Create fix branch
- Locate and diagnose issue
- Fix with regression test
- Verify all tests pass
- Ask for commit confirmation
When I say "review [file/path]"
- Read the file(s)
- Check for:
- TypeScript errors
- Performance issues
- Security vulnerabilities
- Code convention compliance
- Provide structured feedback
Team-Specific Rules
Code Review Focus Areas
- Type safety
- Error handling
- Performance (unnecessary re-renders)
- Security (user input validation)
- Accessibility
- Test coverage
Performance Guidelines
- Component render time: under 16ms
- Page load time: under 2s
- API response time: under 500ms
- Bundle size: under 200KB (gzipped)
Security Requirements
- All user inputs must be validated
- Sanitize data from external sources
- Use HTTPS for API calls
- Implement rate limiting
- Store secrets in environment variables
Integration Points
External Services
- API Base URL: process.env.API_BASE_URL
- Auth Provider: [Auth0/Firebase Auth/etc]
- Analytics: [Google Analytics/Mixpanel]
- Error Tracking: [Sentry/LogRocket]
MCP Connections
- Jira Integration: enabled
- Figma Design System: connected
- API Documentation: linked
Onboarding Checklist
For new team members:
- Read CLAUDE.md
- Set up development environment
- Run local project successfully
- Complete first small task
- Review code standards document
- Join team communication channels
Maintenance
Review Schedule: Monthly Reviewers: Tech Lead + Senior Developers Update Process:
- Propose changes in team meeting
- Discuss and vote
- Update CLAUDE.md
- Announce changes to team
- Version control all updates
Notes:
- This file is version controlled
- All team members should contribute updates
- When in doubt, ask the Tech Lead
- Keep it concise - target under 2000 tokens
#### 環境特定配置
**開發環境 CLAUDE.md.dev:**
```markdown
# Development Environment Additions
## Development Tools
- Hot reload: enabled
- Debug mode: enabled
- Mock data: /mock/data/
- DevTools: Redux DevTools, React DevTools
## Debugging Commands
npm run debug # Start with debug port
npm run mock:api # Start mock API server
npm run inspect # Inspect webpack bundle
## Local Development
- Use mock API when backend is unavailable
- Enable verbose logging
- Test with production build locally before deploying
生產環境 CLAUDE.md.prod:
# Production Environment Guidelines
## Deployment Checklist
- [ ] All tests pass
- [ ] Linting passes
- [ ] TypeScript compiles
- [ ] Bundle size acceptable
- [ ] Environment variables set
- [ ] Migration scripts tested
- [ ] Rollback plan ready
## Production Monitoring
- Monitor error rates in [Error Tracker]
- Check performance metrics
- Review API response times
- Validate database query performance
## Emergency Procedures
If critical bug found:
1. Assess severity
2. Create hotfix branch
3. Fix and test locally
4. Deploy to staging
5. Get quick approval
6. Deploy to production
7. Monitor for 1 hour
8. Create follow-up issue for thorough fix
版本控制CLAUDE.md
配置檔案版本策略
# 推荐的文件结构
.claude/
├── CLAUDE.md # 主配置(当前版本)
├── CLAUDE.md.v1.0.0 # 版本1.0.0
├── CLAUDE.md.v1.1.0 # 版本1.1.0
├── CLAUDE.md.template # 新项目模板
└── CHANGELOG.md # 配置变更日志
# 每次重大更新时
1. 备份当前版本: CLAUDE.md -> CLAUDE.md.v{version}
2. 更新主配置: CLAUDE.md
3. 记录变更: CHANGELOG.md
4. 提交并打标签: git tag claude-config/v{version}
團隊同步機制
自動化同步指令碼:
# scripts/sync-claude-config.sh
#!/bin/bash
# 检查远程配置更新
echo "Checking for CLAUDE.md updates..."
git fetch origin main
REMOTE_VERSION=$(git show origin/main:.claude/CLAUDE.md | grep "Version:" | awk '{print $2}')
LOCAL_VERSION=$(grep "Version:" .claude/CLAUDE.md | awk '{print $2}')
if [ "$REMOTE_VERSION" != "$LOCAL_VERSION" ]; then
echo "New version available: $REMOTE_VERSION (current: $LOCAL_VERSION)"
echo "Run 'git pull origin main' to update"
else
echo "Configuration is up to date"
fi
新增到package.json:
{
"scripts": {
"claude:check": "bash scripts/sync-claude-config.sh",
"claude:update": "git pull origin main -- .claude/",
"precommit": "npm run claude:check"
}
}
團隊配置評審流程
月度配置評審會議模板:
## CLAUDE.md Review Meeting - [Month] [Year]
### Attendees
- Tech Lead
- Senior Developers
- Representative from each squad
### Agenda (30 minutes)
#### 1. Review Current Issues (5 min)
- What's working well?
- What's causing confusion?
- What needs clarification?
#### 2. Proposed Changes (15 min)
Discuss each proposed change:
**Change Proposal 1:**
- **Proposed by:** [Name]
- **Description:** [What and why]
- **Impact:** [Who is affected]
- **Discussion:** [Pros/Cons]
- **Vote:** [Approved/Rejected/Needs revision]
**Change Proposal 2:**
...
#### 3. Action Items (10 min)
- [ ] Update CLAUDE.md with approved changes
- [ ] Announce changes to team
- [ ] Update documentation
- [ ] Schedule training if needed
### Action Items Tracking
| Item | Owner | Due Date | Status |
|------|-------|----------|--------|
| ... | ... | ... | ... |
程式碼審查流程最佳化
AI輔助程式碼審查
審查檢查清單自動化
建立審查模板 .github/PULL_REQUEST_TEMPLATE.md:
## PR Description
<!-- Claude Code: Generate PR description based on commits -->
## Changes Made
<!-- Claude Code: List files changed and summary -->
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests pass
- [ ] Manual testing completed
## Claude Code Pre-Review
<!-- Automated checks run by Claude Code -->
### Code Quality
- [ ] TypeScript: No errors
- [ ] Linting: Passes
- [ ] Tests: All pass
- [ ] Coverage: Above threshold
### Best Practices
- [ ] Follows project conventions
- [ ] No hardcoded values
- [ ] Proper error handling
- [ ] Accessible (if UI)
- [ ] Performance conscious
### Security
- [ ] No sensitive data exposed
- [ ] Input validation present
- [ ] Dependencies up to date
## Manual Review Focus
<!-- Human reviewers should focus on -->
1. Business logic correctness
2. User experience impact
3. Edge cases consideration
4. Long-term maintainability
## Notes
<!-- Any additional context for reviewers -->
整合到CI/CD
GitHub Actions工作流 .github/workflows/claude-review.yml:
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
claude-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install Claude Code
run: |
curl -fsSL https://claude.ai/install.sh | bash
- name: Run Claude Code Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
# 获取变更的文件
CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }})
# 运行Claude Code审查
claude -p "
Review these changed files for:
1. TypeScript type safety
2. Code convention compliance
3. Performance issues
4. Security vulnerabilities
5. Best practices adherence
Files: $CHANGED_FILES
Output a JSON report with:
- overall_score (0-100)
- issues_found (array with severity, file, line, description, suggestion)
- positive_highlights (array)
"
- name: Comment PR with Results
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const report = JSON.parse(fs.readFileSync('claude-review-report.json', 'utf8'));
const body = `
## 🤖 Claude Code Review Report
**Overall Score:** ${report.overall_score}/100
### Issues Found: ${report.issues_found.length}
${report.issues_found.map(issue => `
#### ${issue.severity}: ${issue.title}
- **File:** \`${issue.file}:${issue.line}\`
- **Description:** ${issue.description}
- **Suggestion:** ${issue.suggestion}
`).join('\n')}
### ✨ Positive Highlights
${report.positive_highlights.map(h => `- ${h}`).join('\n')}
`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: body
});
分層審查策略
三層審查模型
第一層: AI自動化審查 (即時)
## Automated Checks (Claude Code)
### What Claude Checks
1. **Syntax & Types**
- TypeScript compilation
- Type correctness
- Import/export validity
2. **Code Conventions**
- Naming conventions
- File structure
- Code formatting
3. **Basic Quality**
- Function length
- File size
- Cyclomatic complexity
4. **Security Basics**
- Hardcoded secrets
- SQL injection risks
- XSS vulnerabilities
### Output Format
```json
{
"status": "pass/fail/warning",
"checks": {
"typescript": {"status": "pass", "errors": 0},
"conventions": {"status": "warning", "issues": ["..."]},
"quality": {"status": "pass", "metrics": {...}}
},
"summary": "3 warnings found"
}
Integration
Runs automatically on every commit and PR
**第二層: AI深度審查 (15分鐘內)**
```markdown
## Deep Analysis (Claude Code)
### Trigger Conditions
- PR has >5 files changed
- Affects critical paths (auth, payments, etc.)
- New feature implementation
- Performance-sensitive code
### What Claude Analyzes
1. **Architecture & Design**
- Code organization
- Separation of concerns
- Design patterns usage
- Coupling and cohesion
2. **Performance**
- Algorithm efficiency
- Memory usage
- Database queries
- Network requests
- React rendering optimization
3. **Maintainability**
- Code duplication
- Naming clarity
- Comment quality
- Test coverage
- Documentation
4. **Business Logic**
- Edge cases
- Error handling
- Validation completeness
- Business rule enforcement
### Review Report Format
```markdown
## Claude Code Deep Review
### 📊 Architecture Assessment
**Score:** 85/100
- Modular design: ✓
- Separation of concerns: ✓
- Design patterns: ⚠️ (Consider using Factory pattern here)
### ⚡ Performance Analysis
**Score:** 78/100
**Issues:**
1. N+1 query problem in `getUserOrders()`
- Location: `src/services/userService.ts:45`
- Impact: High (10x slower with 100 orders)
- Fix: Use eager loading with joins
### 🔒 Security Review
**Score:** 95/100
- Input validation: ✓
- Authentication: ✓
- Authorization: ✓
- Sensitive data: ⚠️ (Log statement may expose email)
### 🧪 Test Coverage
**Score:** 72/100
- Unit tests: 68%
- Integration tests: 45%
- Missing: Error edge cases
### 💡 Recommendations
1. Extract validation logic to separate module
2. Add caching for frequently accessed data
3. Implement retry logic for API calls
4. Add integration tests for new endpoints
**第三層: 人工審查 (24小時內)**
```markdown
## Human Review (Focus Areas)
### What to Focus On
Since Claude Code has handled automated checks, focus on:
1. **Business Correctness**
- Does it solve the right problem?
- Are business rules correctly implemented?
- User experience considerations
2. **Strategic Decisions**
- Long-term implications
- Trade-offs made
- Future extensibility
3. **Team Context**
- Alignment with team goals
- Impact on other work
- Knowledge sharing opportunities
4. **Mentorship**
- Teaching moments
- Best practice demonstrations
- Alternative approaches
### Review Template
```markdown
## Human Review
### 👍 Approvals
- [ ] Business logic correct
- [ ] Ready to merge
- [ ] Needs changes
### 💭 Thoughts & Questions
<!-- What should the author consider? -->
### 🎓 Learning Points
<!-- What can others learn from this PR? -->
### 🔄 Follow-up Actions
<!-- Any issues or improvements to track -->
审查效率提升技巧
批量审查助手
创建批量审查命令:
## Batch Review Commands
### Review Multiple PRs
When I say "review all open PRs":
1. List all open PRs
2. For each PR:
a. Read changed files
b. Run automated checks
c. Generate review summary
3. Create consolidated report
4. Post as team message
### Review by Author
When I say "review PRs by @author":
1. Filter PRs by author
2. Check author's historical patterns
3. Focus on common issues for this author
4. Provide personalized feedback
### Review by Component
When I say "review authentication-related PRs":
1. Identify PRs touching auth code
2. Apply security-focused review
3. Check for common auth vulnerabilities
4. Verify compliance with auth standards
审查质量追踪
建立审查指标看板:
## Code Review Metrics Dashboard
### Team Metrics (Updated Weekly)
#### Review Speed
- **Avg Time to First Review:** 2.3 hours
- **Avg Time to Merge:** 18 hours
- **Goal:** <24 hours to merge
#### Review Quality
- **Bugs Found in Review:** 12% of total bugs
- **Post-deploy Issues:** 3% of PRs
- **Avg Review Comments:** 4.2 per PR
#### Participation
- **Most Active Reviewer:** @sarah (45 reviews)
- **Review Coverage:** 89% of PRs reviewed
- **Avg Reviewers per PR:** 2.1
### Individual Metrics
#### @john_doe
- Reviews Given: 28
- Reviews Received: 15
- Avg Response Time: 1.8 hours
- Common Feedback: Performance optimization
- Strength: Security reviews
- Growth Area: Test coverage reviews
#### @jane_smith
- Reviews Given: 32
- Reviews Received: 18
- Avg Response Time: 2.5 hours
- Common Feedback: Code organization
- Strength: Architecture reviews
- Growth Area: Providing specific examples
### Quality Trends
[Review Time Trend Chart] [Bug Detection Rate Chart] [Team Participation Chart]
提交规范自动化
智能Commit Message生成
配置自动生成
添加到CLAUDE.md:
## Git Commit Standards
### Commit Message Format
Follow Conventional Commits:
- feat: New feature
- fix: Bug fix
- docs: Documentation changes
- style: Code style changes (formatting)
- refactor: Code refactoring
- perf: Performance improvements
- test: Adding/updating tests
- chore: Maintenance tasks
### Auto-Generate Commit Messages
When I say "commit these changes":
1. Analyze git diff
2. Categorize changes (feat/fix/etc)
3. Generate commit message following format
4. Include scope if applicable
5. Ask for confirmation before committing
### Example Output
Input: "commit these changes"
Output:
feat(auth): add OAuth2 login support
- Implement Google OAuth2 flow
- Add JWT token management
- Create login callback handler
- Update auth context
Closes #123
Confirm? [Y/n]
多语言支持
中文commit message支持:
## 中文Commit Message支援
### Bilingual Commits
When committing, generate both English and Chinese:
```bash
feat(user): add user profile page
feat(用户): 添加用户资料页面
- 添加用户信息展示
- 实现头像上传功能
- 添加资料编辑表单
Closes #456
Language Preference
Add to CLAUDE.md:
## Language Settings
- Primary commit language: Chinese
- Secondary: English
- Generate bilingual commits: true
### Commit Hooks集成
#### Pre-commit检查
**`.husky/pre-commit`:**
```bash
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Claude Code預提交檢查
echo "🤖 Running Claude Code pre-commit checks..."
# 獲取暫存的檔案
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)
if [ -z "$STAGED_FILES" ]; then
echo "No staged files to check"
exit 0
fi
# 執行Claude Code檢查
claude -p "
檢查這些暫存檔案的提交 質量:
檔案: $STAGED_FILES
檢查項:
1. TypeScript型別錯誤
2. 程式碼規範違規
3. 明顯的bug
4. 安全問題
5. 效能問題
如果有阻止提交的問題,返回退出碼1
如果有警告,顯示但不阻止提交
" || {
echo "❌ Pre-commit checks failed. Please fix issues before committing."
exit 1
}
echo "✅ Pre-commit checks passed"
Commit-msg验证
.husky/commit-msg:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# 使用Claude Code驗證commit message
COMMIT_MSG_FILE=$1
COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")
claude -p "
驗證這個commit message是否符合規範:
Message: $COMMIT_MSG
規範要求:
1. 遵循Conventional Commits格式
2. subject行不超過72字元
3. 使用祈使句語氣
4. 不以句號結尾
5. 包含有意義的描述
如果不符合規範,提供改進建議並返回退出碼1
" || {
echo "❌ Commit message does not follow conventions"
echo "Expected format: <type>(<scope>): <subject>"
exit 1
}
自动化Changelog生成
使用Claude Code生成changelog:
## Changelog Automation
### Weekly Changelog
When I say "generate changelog":
1. Get commits from last week
2. Categorize by type
3. Group by feature/fix
4. Generate markdown changelog
5. Include links to commits/PRs
6. Highlight breaking changes
### Output Format
```markdown
# Changelog - Week of [Date]
## 🚀 Features
### User Authentication
- feat(auth): add OAuth2 login (abc123) - PR #456
- feat(auth): implement password reset (def456) - PR #457
### Dashboard
- feat(dashboard): add analytics widgets (ghi789) - PR #460
## 🐛 Bug Fixes
### API
- fix(api): resolve timeout issues (jkl012) - PR #463
### UI
- fix(ui): correct mobile responsive issues (mno345) - PR #465
## 🔧 Maintenance
- chore(deps): upgrade React to 18.2.0 (pqr678) - PR #468
- docs: update API documentation (stu901) - PR #470
## 🔄 Breaking Changes
- feat(auth): migrate to JWT tokens (vwx234) - PR #456
- Action required: Update token handling in client apps
- Migration guide: [link]
Release Changelog
When I say "prepare release X.Y.Z":
- Get all commits since last release
- Identify breaking changes
- Group significant changes
- Generate user-friendly changelog
- Create release notes
- Generate migration guide if needed
## 文档协作
### 智能文档生成
#### API文档自动生成
**配置文档生成规则:**
```markdown
## API Documentation Generation
### When Creating API Endpoints
When I create new API routes:
1. Automatically generate OpenAPI/Swagger spec
2. Create JSDoc comments
3. Add usage examples
4. Document request/response schemas
5. Include error responses
### Example Template
```typescript
/**
* Get user by ID
*
* @route GET /api/users/:id
* @description Retrieves a single user by their ID
* @access Private (requires authentication)
*
* @param {string} id.path.required - User ID
* @param {string} authorization.header.required - Bearer token
*
* @returns {UserResponse} 200 - User object
* @returns {ErrorResponse} 404 - User not found
* @returns {ErrorResponse} 401 - Unauthorized
*
* @example
* // Request
* GET /api/users/123
* Authorization: Bearer eyJhbGc...
*
* // Response 200
* {
* "success": true,
* "data": {
* "id": "123",
* "name": "John Doe",
* "email": "john@example.com"
* }
* }
*
* @example
* // Response 404
* {
* "success": false,
* "error": "User not found"
* }
*/
export async function getUserById(req: Request, res: Response) {
// Implementation
}
Auto-Update Documentation
After code changes:
- Detect API modifications
- Update OpenAPI spec
- Regenerate documentation site
- Create PR with docs changes
#### 组件文档生成
**React组件文档模板:**
```markdown
## Component Documentation
### When Creating React Components
Generate documentation including:
1. **Component Description**
- Purpose and usage
- When to use it
- When NOT to use it
2. **Props API**
- Prop names and types
- Required vs optional
- Default values
- Usage examples
3. **State & Callbacks**
- Internal state (if relevant)
- Callback props
- Event handlers
4. **Examples**
- Basic usage
- Advanced usage
- Common patterns
- Edge cases
### Template
```tsx
/**
* UserProfile Component
*
* Displays user profile information with avatar and details.
*
* @whenToUse Use in user profile pages, account settings, user lists
* @whenNotToUse Don't use for editing profiles (use UserProfileForm instead)
*
* @example
* // Basic usage
* <UserProfile
* userId="123"
* onEdit={() => navigate('/edit')}
* />
*
* @example
* // With custom actions
* <UserProfile
* userId="123"
* showEmail={false}
* actions={
* <Button onClick={handleMessage}>Message</Button>
* }
* />
*/
interface UserProfileProps {
/** The unique identifier of the user */
userId: string;
/** Show user's email address */
showEmail?: boolean;
/** Custom action buttons */
actions?: React.ReactNode;
/** Callback when edit button clicked */
onEdit?: () => void;
/** Callback when user not found */
onError?: (error: Error) => void;
}
export const UserProfile: React.FC<UserProfileProps> = ({
userId,
showEmail = true,
actions,
onEdit,
onError
}) => {
// Component implementation
};
文件維護自動化
程式碼-文件同步
配置自動同步:
## Documentation Sync
### Keep Docs in Sync with Code
#### Strategy 1: Doc Comments as Source
- Write documentation in code comments
- Use Claude Code to extract and format
- Generate docs site from comments
- Commit both code and docs together
#### Strategy 2: Separate Docs, Auto-Sync
- Maintain separate documentation files
- When code changes, Claude Code:
1. Detects affected docs
2. Proposes updates
3. Creates PR with doc changes
4. Links code PR to docs PR
### Implementation
```markdown
## Sync Command
When I say "sync docs for this change":
1. Identify files changed in current branch
2. Find related documentation files
3. Analyze what needs updating
4. Generate documentation updates
5. Create separate PR for docs changes
6. Link to code PR
Example:
Input: "sync docs for this change"
Output:
"Detected changes to src/api/users.ts
Related docs: docs/api/users.md
Updates needed:
- Update endpoint descriptions
- Add new POST /api/users/:id/archive endpoint
- Update request/response examples
Created PR #789 with documentation updates"
过期文档检测
定期文档审计:
## Documentation Audit
### Weekly Documentation Check
When I say "audit documentation":
1. Compare docs to current code
2. Identify outdated sections
3. Find undocumented features
4. Check example code accuracy
5. Verify links and references
### Audit Report Template
```markdown
# Documentation Audit Report - [Date]
## 📊 Summary
- Total docs pages: 45
- Up to date: 38 (84%)
- Need updates: 5 (11%)
- Missing: 2 (4%)
## ⚠️ Outdated Documentation
### 1. API Authentication
**File:** docs/api/authentication.md
**Issues:**
- References old OAuth flow
- Example code uses deprecated methods
- Missing new token refresh logic
**Recommendation:** Update with new OAuth2.0 implementation
### 2. Component Library
**File:** docs/components/Button.md
**Issues:**
- Props list missing new `variant` prop
- Examples don't show new 'danger' variant
**Recommendation:** Add variant documentation
## 🆕 Missing Documentation
### 1. Error Boundary Component
**Component:** ErrorBoundary.tsx
**Status:** Implemented but not documented
**Priority:** High (used in 5+ places)
### 2. useDebounce Hook
**Hook:** hooks/useDebounce.ts
**Status:** Implemented but not documented
**Priority:** Medium (used internally)
## 🔗 Broken Links
- [ ] docs/guides/testing.md → #performance-section (404)
- [ ] docs/api/users.md → examples/user-example.ts (missing)
## 📝 Action Items
- [ ] Update authentication docs (assign: @tech-writer)
- [ ] Document ErrorBoundary (assign: @john)
- [ ] Fix broken links (assign: @jane)
- [ ] Add changelog to release notes (assign: @all)
### 协作式文档编写
#### 实时协作编辑
**团队文档协作流程:**
```markdown
## Collaborative Documentation
### Live Editing Sessions
#### Setup
1. Create shared doc in team workspace
2. Invite team members to edit
3. Use Claude Code as facilitator:
- Suggest structure
- Fill in sections
- Resolve conflicts
- Maintain consistency
#### Template for Team Doc Session
```markdown
# [Document Title]
**Authors:** @name1, @name2, @name3
**Last Updated:** [Date]
**Status:** Draft | Review | Approved
## Outline
- [ ] Section 1 (assigned to @name1)
- [ ] Section 2 (assigned to @name2)
- [ ] Section 3 (assigned to @name3)
---
## Section 1: [Title]
<!-- @name1: Write this section -->
<!-- Claude: Provide structure and suggestions -->
## Section 2: [Title]
<!-- @name2: Write this section -->
## Section 3: [Title]
<!-- @name3: Write this section -->
## Review Checklist
- [ ] Technical accuracy
- [ ] Clear and concise
- [ ] Examples work
- [ ] Links valid
- [ ] Formatting consistent
Claude Code Facilitation
When I say "facilitate doc session":
- Monitor document changes
- Suggest improvements in real-time
- Fix formatting inconsistencies
- Ensure all sections covered
- Generate summary of session
#### 知识库构建
**团队知识库模板:**
```markdown
## Team Knowledge Base
### Structure
docs/knowledge-base/ ├── onboarding/ # 新人入职 │ ├── setup.md │ ├── first-week.md │ └── common-tasks.md ├── troubleshooting/ # 问题解决 │ ├── common-errors.md │ ├── debug-guide.md │ └── performance-issues.md ├── decisions/ # 技术决策记录 │ ├── architecture.md │ ├── technology-choice.md │ └── trade-offs.md ├── patterns/ # 代码模式 │ ├── react-patterns.md │ ├── api-patterns.md │ └── state-management.md └── workflows/ # 工作流程 ├── deployment.md ├── testing.md └── code-review.md
### Auto-Populate Knowledge Base
When solving problems:
1. Ask Claude to document solution
2. Add to appropriate KB section
3. Link from related docs
4. Tag with relevant keywords
Example:
Input: "Document this solution in KB"
Output: "Added to docs/knowledge-base/troubleshooting/performance-issues.md
Tagged: #performance #optimization #database
Linked from: docs/api/database.md, docs/guides/performance.md"