Skip to content

improve - 代码改进命令

improve 命令是 Claude Code 的智能代码优化工具,基于分析结果自动改进代码质量、性能和安全性。

命令概述

improve 命令提供:

  • 自动代码重构
  • 性能优化建议
  • 安全漏洞修复
  • 代码规范化
  • 代码清理

基本用法

自动改进

bash
# 改进整个项目
claude improve

# 改进指定文件
claude improve ./src/components/UserProfile.jsx

# 改进指定目录
claude improve ./src/utils

按类型改进

bash
# 性能优化
claude improve --type performance

# 安全修复
claude improve --type security

# 代码质量提升
claude improve --type quality

# 代码风格规范化
claude improve --type style

改进模式

bash
# 安全模式 (只进行安全的改进)
claude improve --mode safe

# 建议模式 (生成改进建议但不修改)
claude improve --mode suggest

# 激进模式 (进行更深度的重构)
claude improve --mode aggressive

配置选项

基础选项

选项类型默认值描述
--typestringall改进类型
--modestringsafe改进模式
--dry-runbooleanfalse预览模式,不实际修改
--backupbooleantrue是否创建备份

范围控制

选项类型默认值描述
--includestring-包含的文件模式
--excludestring-排除的文件模式
--max-changesnumber50最大修改数量
--confidencestringhigh最低置信度: low, medium, high

改进类型详解

1. 性能优化 (Performance)

React 组件优化

bash
# React 性能优化
claude improve --type performance --focus react

改进示例:

jsx
// 改进前
const ProductList = ({ products, onSelect }) => {
  const [filter, setFilter] = useState('');
  
  const filteredProducts = products.filter(product => 
    product.name.toLowerCase().includes(filter.toLowerCase())
  );
  
  return (
    <div>
      <input onChange={e => setFilter(e.target.value)} />
      {filteredProducts.map(product => (
        <ProductCard 
          key={product.id}
          product={product}
          onClick={() => onSelect(product)}
        />
      ))}
    </div>
  );
};

// 改进后
const ProductList = React.memo(({ products, onSelect }) => {
  const [filter, setFilter] = useState('');
  
  //  缓存过滤结果
  const filteredProducts = useMemo(() => 
    products.filter(product => 
      product.name.toLowerCase().includes(filter.toLowerCase())
    ), [products, filter]
  );
  
  //  缓存回调函数
  const handleSelect = useCallback((product) => {
    onSelect(product);
  }, [onSelect]);
  
  return (
    <div>
      <input onChange={e => setFilter(e.target.value)} />
      {filteredProducts.map(product => (
        <MemoizedProductCard 
          key={product.id}
          product={product}
          onSelect={handleSelect}
        />
      ))}
    </div>
  );
});

//  子组件优化
const MemoizedProductCard = React.memo(({ product, onSelect }) => {
  const handleClick = useCallback(() => {
    onSelect(product);
  }, [product, onSelect]);
  
  return (
    <div onClick={handleClick}>
      <h3>{product.name}</h3>
      <p>{product.price}</p>
    </div>
  );
});

数据库查询优化

bash
# 数据库性能优化
claude improve --type performance --focus database

改进示例:

javascript
// 改进前 - N+1 查询问题
const getUsersWithPosts = async () => {
  const users = await User.findAll();
  for (let user of users) {
    user.posts = await Post.findAll({ where: { userId: user.id } });
  }
  return users;
};

// 改进后 - 使用 JOIN 查询
const getUsersWithPosts = async () => {
  return await User.findAll({
    include: [{
      model: Post,
      as: 'posts'
    }]
  });
};

// 或者使用 DataLoader 模式
const postLoader = new DataLoader(async (userIds) => {
  const posts = await Post.findAll({
    where: { userId: { [Op.in]: userIds } }
  });
  
  const postsByUserId = {};
  posts.forEach(post => {
    if (!postsByUserId[post.userId]) {
      postsByUserId[post.userId] = [];
    }
    postsByUserId[post.userId].push(post);
  });
  
  return userIds.map(id => postsByUserId[id] || []);
});

const getUsersWithPosts = async () => {
  const users = await User.findAll();
  for (let user of users) {
    user.posts = await postLoader.load(user.id);
  }
  return users;
};

2. 安全修复 (Security)

输入验证和净化

bash
# 安全漏洞修复
claude improve --type security

改进示例:

javascript
// 改进前 - SQL 注入风险
const getUserById = async (userId) => {
  const query = `SELECT * FROM users WHERE id = ${userId}`;
  return await db.query(query);
};

// 改进后 - 参数化查询
const getUserById = async (userId) => {
  //  输入验证
  if (!userId || typeof userId !== 'string') {
    throw new Error('无效的用户ID');
  }
  
  //  参数化查询
  const query = 'SELECT * FROM users WHERE id = ?';
  return await db.query(query, [userId]);
};

// 改进前 - XSS 风险
const renderUserContent = (content) => {
  return `<div>${content}</div>`;
};

// 改进后 - HTML 净化
import DOMPurify from 'dompurify';

const renderUserContent = (content) => {
  //  HTML 净化
  const cleanContent = DOMPurify.sanitize(content, {
    ALLOWED_TAGS: ['p', 'br', 'strong', 'em'],
    ALLOWED_ATTR: []
  });
  
  return `<div>${cleanContent}</div>`;
};

敏感信息保护

javascript
// 改进前 - 硬编码密钥
const JWT_SECRET = 'my-secret-key-123';
const API_KEY = 'sk-1234567890abcdef';

// 改进后 - 环境变量
const JWT_SECRET = process.env.JWT_SECRET;
const API_KEY = process.env.API_KEY;

//  配置验证
if (!JWT_SECRET) {
  throw new Error('JWT_SECRET 环境变量未设置');
}

// 改进前 - 明文密码
const user = {
  email: 'user@example.com',
  password: 'plaintext-password'
};

// 改进后 - 密码哈希
import bcrypt from 'bcrypt';

const hashPassword = async (password) => {
  const saltRounds = 12;
  return await bcrypt.hash(password, saltRounds);
};

const user = {
  email: 'user@example.com',
  passwordHash: await hashPassword('user-password')
};

3. 代码质量提升 (Quality)

复杂度简化

bash
# 代码质量改进
claude improve --type quality --focus complexity

改进示例:

javascript
// 改进前 - 高复杂度函数
const processUserData = (user) => {
  if (user && user.age) {
    if (user.age >= 18) {
      if (user.isActive) {
        if (user.hasSubscription) {
          if (user.subscription.type === 'premium') {
            return 'premium-active-adult';
          } else if (user.subscription.type === 'basic') {
            return 'basic-active-adult';
          } else {
            return 'unknown-active-adult';
          }
        } else {
          return 'no-subscription-active-adult';
        }
      } else {
        return 'inactive-adult';
      }
    } else {
      return 'minor';
    }
  } else {
    return 'invalid-user';
  }
};

// 改进后 - 提取小函数,降低复杂度
const isValidUser = (user) => user && typeof user.age === 'number';

const isAdult = (user) => user.age >= 18;

const getSubscriptionType = (user) => {
  if (!user.hasSubscription) return 'none';
  return user.subscription?.type || 'unknown';
};

const getUserCategory = (user) => {
  if (!isValidUser(user)) return 'invalid-user';
  if (!isAdult(user)) return 'minor';
  if (!user.isActive) return 'inactive-adult';
  
  const subscriptionType = getSubscriptionType(user);
  
  switch (subscriptionType) {
    case 'premium': return 'premium-active-adult';
    case 'basic': return 'basic-active-adult';
    case 'none': return 'no-subscription-active-adult';
    default: return 'unknown-active-adult';
  }
};

//  或者使用策略模式
const userCategoryStrategies = {
  invalid: () => 'invalid-user',
  minor: () => 'minor',
  inactiveAdult: () => 'inactive-adult',
  activeAdult: (subscriptionType) => {
    const typeMap = {
      premium: 'premium-active-adult',
      basic: 'basic-active-adult',
      none: 'no-subscription-active-adult'
    };
    return typeMap[subscriptionType] || 'unknown-active-adult';
  }
};

const processUserData = (user) => {
  if (!isValidUser(user)) return userCategoryStrategies.invalid();
  if (!isAdult(user)) return userCategoryStrategies.minor();
  if (!user.isActive) return userCategoryStrategies.inactiveAdult();
  
  const subscriptionType = getSubscriptionType(user);
  return userCategoryStrategies.activeAdult(subscriptionType);
};

代码重复消除

javascript
// 改进前 - 重复代码
const validateEmail = (email) => {
  if (!email) return false;
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

const validatePhone = (phone) => {
  if (!phone) return false;
  const phoneRegex = /^\+?[\d\s-()]+$/;
  return phoneRegex.test(phone);
};

const validateName = (name) => {
  if (!name) return false;
  const nameRegex = /^[a-zA-Z\s]+$/;
  return nameRegex.test(name);
};

// 改进后 - 通用验证函数
const createValidator = (regex, errorMessage) => {
  return (value) => {
    if (!value) {
      return { isValid: false, error: '此字段是必填的' };
    }
    
    const isValid = regex.test(value);
    return {
      isValid,
      error: isValid ? null : errorMessage
    };
  };
};

//  使用工厂函数创建验证器
const validators = {
  email: createValidator(
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
    '请输入有效的邮箱地址'
  ),
  phone: createValidator(
    /^\+?[\d\s-()]+$/,
    '请输入有效的电话号码'
  ),
  name: createValidator(
    /^[a-zA-Z\s]+$/,
    '姓名只能包含字母和空格'
  )
};

// 使用示例
const emailValidation = validators.email('user@example.com');
console.log(emailValidation); // { isValid: true, error: null }

4. 代码风格规范化 (Style)

ESLint/Prettier 规范化

bash
# 代码风格改进
claude improve --type style

改进示例:

javascript
// 改进前 - 不一致的代码风格
const users=[{name:"John",age:25},{name:"Jane",age:30}];

function getUser(id ){
    if(id){
        const user=users.find(u=>u.id===id)
        return user
    }else{
        return null
    }
}

// 改进后 - 规范化的代码风格
const users = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 }
];

const getUser = (id) => {
  if (!id) {
    return null;
  }
  
  return users.find(user => user.id === id) || null;
};

//  更好的实现
const getUser = (id) => {
  if (!id) {
    throw new Error('用户ID是必需的');
  }
  
  const user = users.find(user => user.id === id);
  
  if (!user) {
    throw new Error(`用户 ${id} 不存在`);
  }
  
  return user;
};

改进报告

生成改进报告

bash
# 生成详细改进报告
claude improve --report improvement-report.html

# 预览改进效果
claude improve --dry-run --verbose

示例报告:

代码改进报告
============

 改进统计:
• 文件修改: 23 个
• 性能优化: 12 处
• 安全修复: 5 处
• 代码简化: 18 处
• 风格规范: 45 处

 性能提升:
• React 组件渲染: 平均提升 40%
• 数据库查询: 减少 60% 的查询次数
• 内存使用: 降低 25% 的内存占用

 安全加固:
• SQL 注入风险: 修复 3 处
• XSS 攻击风险: 修复 2 处
• 敏感信息泄漏: 修复 1 处

 代码质量:
• 平均圈复杂度: 8.2 → 5.1 (降低 38%)
• 代码重复率: 15% → 8% (降低 47%)
• 函数平均长度: 32 行 → 18 行 (降低 44%)

 改进详情:

1. 性能优化: React 组件缓存
   文件: src/components/ProductList.jsx
   改进: 添加 React.memo 和 useMemo
   预期收益: 渲染性能提升 40%

2. 安全修复: SQL 注入防护
   文件: src/services/userService.js
   改进: 使用参数化查询
   风险等级: HIGH → RESOLVED

3. 代码简化: 函数复杂度降低
   文件: src/utils/validation.js
   改进: 提取子函数,使用策略模式
   复杂度: 15 → 6

自定义配置

改进配置文件

javascript
// claude.improve.config.js
export default {
  // 改进规则
  rules: {
    performance: {
      react: {
        addMemo: true,
        addCallback: true,
        splitLargeComponents: true
      },
      database: {
        fixNPlus1: true,
        addIndexHints: true,
        optimizeQueries: true
      }
    },
    
    security: {
      inputValidation: true,
      sqlInjection: true,
      xssPrevention: true,
      sensitiveData: true
    },
    
    quality: {
      complexity: {
        maxCyclomatic: 10,
        maxCognitive: 15
      },
      duplication: {
        minLines: 5,
        threshold: 0.8
      }
    },
    
    style: {
      prettier: true,
      eslint: true,
      formatting: true
    }
  },
  
  // 改进模式
  modes: {
    safe: {
      onlyReversible: true,
      preserveLogic: true,
      minConfidence: 0.9
    },
    
    suggest: {
      generateComments: true,
      createTodos: true,
      dryRun: true
    },
    
    aggressive: {
      deepRefactoring: true,
      breakingChanges: false,
      minConfidence: 0.7
    }
  },
  
  // 备份配置
  backup: {
    enabled: true,
    directory: '.claude/backups',
    keepDays: 30
  }
};

自定义改进器

javascript
// improvers/custom-improver.js
export default class CustomImprover {
  constructor(options) {
    this.options = options;
  }
  
  async improve(files) {
    const improvements = [];
    
    for (const file of files) {
      const fileImprovements = await this.improveFile(file);
      improvements.push(...fileImprovements);
    }
    
    return improvements;
  }
  
  async improveFile(file) {
    const improvements = [];
    
    // 自定义改进逻辑
    if (file.path.endsWith('.jsx')) {
      improvements.push(...this.improveReactComponent(file));
    }
    
    if (file.path.includes('service')) {
      improvements.push(...this.improveService(file));
    }
    
    return improvements;
  }
  
  improveReactComponent(file) {
    const improvements = [];
    
    // 检查是否缺少 React.memo
    if (!file.content.includes('React.memo')) {
      improvements.push({
        type: 'performance',
        description: '添加 React.memo 优化',
        confidence: 0.8,
        apply: (content) => {
          // 应用改进的逻辑
          return this.wrapWithMemo(content);
        }
      });
    }
    
    return improvements;
  }
  
  wrapWithMemo(content) {
    // 实现具体的改进逻辑
    return content.replace(
      /const (\w+) = \(([^)]*)\) => {/,
      'const $1 = React.memo(($2) => {'
    ) + '});';
  }
}

集成和自动化

VS Code 扩展集成

json
// .vscode/settings.json
{
  "claude.improve.autoRun": true,
  "claude.improve.onSave": ["style"],
  "claude.improve.schedule": "daily",
  "claude.improve.notifications": true
}

Git Hooks 集成

bash
#!/bin/sh
# .git/hooks/pre-commit

echo "运行代码改进检查..."

# 对暂存的文件运行改进
claude improve --staged --mode suggest

# 如果有高置信度的改进建议,自动应用
claude improve --staged --mode safe --confidence high

echo "代码改进完成"

CI/CD 流水线

yaml
# .github/workflows/improve.yml
name: Code Improvement

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  improve:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Run code improvements
        run: |
          npx claude improve --mode safe --backup
          
      - name: Commit improvements
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git add -A
          git diff --staged --quiet || git commit -m "自动代码改进 [skip ci]"
          git push

相关命令

最佳实践

1. 渐进式改进

  • 从安全模式开始
  • 先修复高优先级问题
  • 逐步应用复杂改进

2. 备份和回滚

  • 始终创建代码备份
  • 测试改进后的代码
  • 准备回滚方案

3. 团队协作

  • 制定改进标准
  • 代码审查改进结果
  • 分享改进经验

4. 持续优化

  • 定期运行改进分析
  • 跟踪改进效果
  • 调整改进配置

improve 命令 - 让代码自我进化

Claude Code 使用指南