以下为本文档的中文说明

file-watcher 是一个文件监听技能,用于配置文件监听钩子,使其能够自动响应配置文件变更、环境文件更新和依赖修改等事件,从而创建响应式的工作流。该技能利用 Claude Code 的 FileChanged 和 CwdChanged 钩子机制来实现文件系统变更的自动响应。其工作原理是通过在 SessionStart 和 CwdChanged 钩子脚本中注册 watchPaths 来监听指定文件路径。当被监听的文件发生变化时,FileChanged 事件会被触发,自动执行预定义的操作。使用场景包括:设置配置文件的热重载机制——当 .env 文件或 config 文件发生变化时自动重新加载配置;监听依赖文件如 package.json 的变化,在依赖更新时自动重新安装;监控构建输出目录,在构建完成时自动触发后续处理流程;以及创建响应式开发工作流,让 AI 代理自动感知环境变化并做出相应调整。该技能支持的监听路径配置格式为 JSON 结构,需要指定钩子事件名称和要监听的绝对路径列表。核心特点包括:基于事件驱动的文件变更响应机制、支持多种钩子事件类型(SessionStart、CwdChanged、FileChanged)、灵活的路径配置方式、与 Claude Code 原生集成的零额外依赖设计、以及自动化的环境感知能力。对于追求开发流程自动化的团队来说,这个技能可以将原本需要手动触发的各种操作转变为自动化的响应式流程,显著提升开发效率。


File Watcher

Use Claude Code’s FileChanged and CwdChanged hooks to create reactive workflows that respond to file system changes.

Trigger

Use when:

  • Setting up auto-reload for config changes
  • Watching for dependency updates
  • Monitoring build output
  • Creating reactive development workflows

How File Watching Works

Claude Code’s SessionStart and CwdChanged hooks support returning watchPaths to register file watchers. The current cwd-changed.js script focuses on env injection; to add watch registration, your hook script must output this JSON structure:

{
  "hookSpecificOutput": {
    "hookEventName": "SessionStart",
    "watchPaths": [
      "/absolute/path/to/.env",
      "/absolute/path/to/package.json"
    ]
  }
}

When watched files change, the FileChanged hook fires with:

{
  "hook_event_name": "FileChanged",
  "file_path": "/path/to/changed/file",
  "event": "change"
}

Environment Injection

CwdChanged and FileChanged hooks can write to CLAUDE_ENV_FILE to inject environment variables into subsequent Bash commands:

echo "export PROJECT_TYPE=node" >> "$CLAUDE_ENV_FILE"
echo "export TEST_CMD='npm test'" >> "$CLAUDE_ENV_FILE"

Common Watch Patterns

Watch .env for Changes

const envFile = path.join(projectRoot, '.env');
if (fs.existsSync(envFile)) {
  output.hookSpecificOutput = {
    hookEventName: 'SessionStart',
    watchPaths: [envFile]
  };
}

Watch package.json for Dependency Changes

Detect when dependencies change and remind to run npm install.

Watch tsconfig.json for Config Changes

Remind to restart TypeScript checks when config changes.

Setup

Add to hooks.json:

{
  "FileChanged": [{
    "matcher": ".env|package.json|tsconfig.json",
    "hooks": [{
      "type": "command",
      "command": "node scripts/file-changed.js"
    }]
  }]
}

Rules

  • Use absolute paths for watchPaths (required by Claude Code)
  • Matcher uses pipe-separated filenames
  • Watcher uses 500ms stability threshold and 200ms poll interval
  • Keep file-changed handlers fast (<5s) to avoid blocking
  • Use CLAUDE_ENV_FILE for injecting env vars, not direct export
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐