Skip to content

AI 规则配置

Trae IDE 允许您为 AI 助手配置自定义规则,以确保生成的代码符合您的项目标准和最佳实践。

概述

AI 规则系统提供以下功能:

  • 代码风格和格式化规则
  • 命名约定和最佳实践
  • 安全性和性能指导
  • 项目特定的约束条件
  • 团队协作标准

规则类型

1. 代码风格规则

缩进和格式化

yaml
style:
  indentation:
    type: "spaces"  # spaces | tabs
    size: 2
  line_length: 100
  trailing_whitespace: false
  final_newline: true

命名约定

yaml
naming:
  variables:
    style: "camelCase"  # camelCase | snake_case | PascalCase
    prefix: ""
    suffix: ""
  functions:
    style: "camelCase"
    async_prefix: ""
  classes:
    style: "PascalCase"
  constants:
    style: "UPPER_SNAKE_CASE"
  files:
    style: "kebab-case"

2. 语言特定规则

JavaScript/TypeScript

yaml
javascript:
  prefer_const: true
  no_var: true
  semicolons: true
  quotes: "single"  # single | double
  arrow_functions: true
  destructuring: true
  template_literals: true
  
typescript:
  strict_mode: true
  explicit_types: "when_needed"  # always | when_needed | never
  interface_over_type: true
  no_any: true

Python

yaml
python:
  line_length: 88
  quotes: "double"
  imports:
    sort: true
    group: true
  type_hints: true
  docstrings:
    style: "google"  # google | numpy | sphinx
    required: true

Java

yaml
java:
  class_naming: "PascalCase"
  method_naming: "camelCase"
  constant_naming: "UPPER_SNAKE_CASE"
  package_naming: "lowercase"
  braces: "same_line"
  access_modifiers: "explicit"

3. 安全规则

yaml
security:
  no_hardcoded_secrets: true
  no_sql_injection: true
  input_validation: true
  output_encoding: true
  secure_random: true
  https_only: true
  
  forbidden_functions:
    - "eval"
    - "exec"
    - "system"
  
  required_headers:
    - "Content-Security-Policy"
    - "X-Frame-Options"

4. 性能规则

yaml
performance:
  avoid_n_plus_one: true
  cache_expensive_operations: true
  lazy_loading: true
  minimize_database_queries: true
  optimize_loops: true
  
  limits:
    max_function_length: 50
    max_class_length: 500
    max_file_length: 1000
    max_complexity: 10

5. 项目特定规则

yaml
project:
  architecture:
    pattern: "mvc"  # mvc | mvp | mvvm | clean
    layers:
      - "presentation"
      - "business"
      - "data"
  
  dependencies:
    allowed_packages:
      - "lodash"
      - "axios"
    forbidden_packages:
      - "moment"  # 使用 date-fns 替代
  
  file_structure:
    components_dir: "src/components"
    utils_dir: "src/utils"
    tests_dir: "__tests__"

配置文件

全局配置

在用户设置中配置全局 AI 规则:

json
{
  "trae.ai.rules": {
    "global": {
      "style": {
        "indentation": {
          "type": "spaces",
          "size": 2
        }
      }
    }
  }
}

项目配置

在项目根目录创建 .trae/ai-rules.yml

yaml
# .trae/ai-rules.yml
version: "1.0"

extends:
  - "@trae/rules-javascript"
  - "@trae/rules-security"

rules:
  style:
    indentation:
      type: "spaces"
      size: 2
    line_length: 100
  
  naming:
    variables: "camelCase"
    functions: "camelCase"
    classes: "PascalCase"
  
  javascript:
    prefer_const: true
    semicolons: true
    quotes: "single"
  
  security:
    no_hardcoded_secrets: true
    input_validation: true
  
  custom:
    api_naming: "RESTful"
    error_handling: "try_catch"
    logging: "structured"

overrides:
  - files: "*.test.js"
    rules:
      naming:
        functions: "snake_case"
  
  - files: "src/components/**"
    rules:
      react:
        hooks_rules: true
        prop_types: true

团队配置

yaml
# .trae/team-rules.yml
team:
  name: "Frontend Team"
  standards:
    code_review: true
    testing: "required"
    documentation: "required"
  
  workflows:
    git:
      branch_naming: "feature/task-id-description"
      commit_message: "conventional"
    
    ci_cd:
      tests: "required"
      linting: "required"
      security_scan: "required"

规则优先级

规则按以下优先级应用:

  1. 项目特定规则 (.trae/ai-rules.yml)
  2. 团队规则 (.trae/team-rules.yml)
  3. 全局用户规则 (用户设置)
  4. 默认规则 (Trae 内置)

规则验证

实时验证

AI 在生成代码时会实时应用规则:

typescript
// AI 会根据规则自动调整代码风格
function calculateTotal(items: Item[]): number {
  return items.reduce((sum, item) => sum + item.price, 0);
}

批量验证

bash
# 验证项目中的所有文件
trae validate --rules .trae/ai-rules.yml

# 验证特定文件
trae validate --rules .trae/ai-rules.yml src/components/Button.tsx

# 自动修复
trae validate --fix --rules .trae/ai-rules.yml

自定义规则

创建自定义规则

yaml
# custom-rules.yml
custom_rules:
  - name: "no_console_log"
    description: "禁止使用 console.log"
    pattern: "console\\.log\\("
    severity: "warning"
    suggestion: "使用结构化日志记录"
  
  - name: "require_error_handling"
    description: "异步函数必须包含错误处理"
    applies_to: "async_functions"
    requires: "try_catch_block"
    severity: "error"

规则插件

typescript
// rules/custom-naming.ts
export class CustomNamingRule implements AIRule {
  name = 'custom-naming';
  description = '自定义命名规则';
  
  validate(code: string, context: ValidationContext): RuleViolation[] {
    const violations: RuleViolation[] = [];
    
    // 检查函数命名
    const functionRegex = /function\s+([a-zA-Z_][a-zA-Z0-9_]*)/g;
    let match;
    
    while ((match = functionRegex.exec(code)) !== null) {
      const functionName = match[1];
      
      if (!this.isValidFunctionName(functionName)) {
        violations.push({
          rule: this.name,
          message: `函数名 "${functionName}" 不符合命名规范`,
          line: this.getLineNumber(code, match.index),
          severity: 'warning',
          suggestion: this.suggestFunctionName(functionName)
        });
      }
    }
    
    return violations;
  }
  
  private isValidFunctionName(name: string): boolean {
    // 实现命名验证逻辑
    return /^[a-z][a-zA-Z0-9]*$/.test(name);
  }
  
  private suggestFunctionName(name: string): string {
    // 提供命名建议
    return name.charAt(0).toLowerCase() + name.slice(1);
  }
}

规则模板

React 项目模板

yaml
# templates/react-project.yml
extends:
  - "@trae/rules-javascript"
  - "@trae/rules-react"
  - "@trae/rules-typescript"

rules:
  react:
    hooks_rules: true
    prop_types: false  # 使用 TypeScript
    jsx_quotes: "double"
    component_naming: "PascalCase"
    
  typescript:
    strict_mode: true
    explicit_return_types: true
    no_any: true
    
  file_structure:
    components: "src/components"
    hooks: "src/hooks"
    utils: "src/utils"
    types: "src/types"

Node.js API 模板

yaml
# templates/nodejs-api.yml
extends:
  - "@trae/rules-javascript"
  - "@trae/rules-nodejs"
  - "@trae/rules-security"

rules:
  nodejs:
    async_await: true
    error_handling: "required"
    logging: "structured"
    
  api:
    rest_conventions: true
    status_codes: "standard"
    error_responses: "consistent"
    
  security:
    input_validation: true
    rate_limiting: true
    authentication: "required"

最佳实践

1. 渐进式采用

yaml
# 开始时使用宽松规则
rules:
  style:
    enforcement: "warning"
  
# 逐步提高要求
rules:
  style:
    enforcement: "error"

2. 团队协作

  • 在团队中统一规则配置
  • 定期审查和更新规则
  • 提供规则培训和文档
  • 收集团队反馈

3. 性能考虑

  • 避免过于复杂的规则
  • 使用缓存提高验证速度
  • 合理设置规则优先级
  • 定期清理无用规则

4. 维护性

  • 使用版本控制管理规则
  • 编写清晰的规则文档
  • 提供规则变更日志
  • 建立规则审查流程

故障排除

常见问题

  1. 规则冲突

    yaml
    # 使用 overrides 解决冲突
    overrides:
      - files: "*.test.js"
        rules:
          naming: "snake_case"
  2. 性能问题

    yaml
    # 限制规则范围
    rules:
      applies_to:
        - "src/**/*.js"
        - "!node_modules/**"
  3. 规则不生效

    • 检查文件路径匹配
    • 验证 YAML 语法
    • 确认规则优先级
    • 重启 IDE

调试工具

bash
# 查看当前规则配置
trae rules --show

# 测试规则匹配
trae rules --test file.js

# 调试规则执行
trae rules --debug --verbose

相关资源

您的终极 AI 驱动 IDE 学习指南