ClaudeCode使用
Claude Code 完全使用指南
一份基于官方文档的全面使用手册,涵盖Claude Code的所有功能、配置和最佳实践。
Claude Code是什么
产品概述
Claude Code是由Anthropic推出的AI编码工具,直接集成在您的终端中。它是一个强大的代码编辑和分析工具,为开发者提供智能代码辅助。
核心功能
1. 构建功能
用英文描述想要构建的功能,Claude会制定计划、编写代码并确保其正常运行。
示例:
"add input validation to the user registration form"
"implement a dark mode toggle in the settings page"
"create a database migration for the new users table"
2. 调试和修复
描述bug或粘贴错误消息,Claude会分析代码库、识别问题并实施修复。
示例:
"fix the login bug where users see a blank screen after entering wrong credentials"
"resolve the memory leak in the background worker"
"fix the TypeScript compilation error in the API module"
3. 代码库导航和理解
提问关于团队代码库的任何内容,获得有思考的答案。Claude能够:
- 维护整个项目结构的认知
- 从网络获取最新信息
- 通过MCP从Google Drive、Figma、Slack等外部数据源提取信息
示例:
"what does this project do?"
"explain the authentication flow in this codebase"
"where are database queries defined?"
"find all endpoints that handle user data"
4. 自动化繁琐任务
- 修复linting问题
- 解决merge conflicts
- 编写发布说明
- 在开发者机器或CI中一条命令完成
示例:
"fix all eslint errors in the project"
"resolve merge conflicts in package-lock.json"
"generate a release notes file for version 2.1.0"
为什么开发者喜欢Claude Code
| 优势 | 说明 |
|---|---|
| 在您的终端中工作 | 不是另一个聊天窗口,不是另一个IDE,而是在您已经使用的工具中 |
| 采取行动 | 直接编辑文件、运行命令、创建commits |
| Unix哲学 | 可组合和可脚本化,支持管道操作 |
| 智能分析 | 深度理解代码结构和上下文 |
| 企业就绪 | 支持AWS Bedrock或GCP,包含企业级安全、隐私和合规 |
| 安全控制 | 细粒度权限管理,可完全控制代码访问 |
安装Claude Code
前置要求
- Claude.ai账户(推荐)或Claude Console账户
- 终端/命令提示符
- 网络连接
安装方法
方法1:原生安装(推荐)
macOS、Linux、WSL:
curl -fsSL https://claude.ai/install.sh | bash
Windows PowerShell(管理员):
irm https://claude.ai/install.ps1 | iex
Windows CMD(管理员):
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
方法2:Homebrew(macOS)
brew install --cask claude-code
方法3:NPM(需要Node.js 18+)
npm install -g @anthropic-ai/claude-code
WSL环境注意事项: 如果遇到OS检测问题,运行:
npm config set os linux
npm install -g @anthropic-ai/claude-code --force --no-os-check
启动和登录
# 进入项目目录
cd /path/to/your/project
# 启动Claude Code
claude
# 首次使用时会提示登录
# 也可以手动触发登录
/login
验证安装
# 检查安装健康状态
claude doctor
# 查看版本和状态信息
claude /status
# 显示帮助信息
claude /help
预期输出应该显示:
- Claude Code版本号
- 当前模型
- 登录账户信息
- 可用的子代理
基本命令和使用方式
核心命令参考
| 命令 | 功能 | 示例 |
|---|---|---|
claude |
启动交互式REPL会话 | claude |
claude "query" |
启动并执行初始提示 | claude "explain this project" |
claude -p "query" |
执行查询然后退出(一次性模式) | claude -p "explain this function" |
cat file | claude -p |
处理管道输入 | cat logs.txt | claude -p "find errors" |
claude -c |
继续最近的对话 | claude -c |
claude -r "session" |
恢复特定命名会话 | claude -r "auth-refactor" |
claude update |
更新到最新版本 | claude update |
claude --continue |
继续最后一个会话 | claude --continue |
claude --resume |
显示会话选择器 | claude --resume |
首次使用建议
第1步:了解项目(5-10分钟)
claude
> what does this project do?
> what technologies does this project use?
> where is the main entry point?
> explain the folder structure
> list the key dependencies
目的: 让Claude理解您的项目后再进行更复杂的任务
第2步:进行小的代码更改(10-15分钟)
> add a hello world function to the main file
Claude会:
- 找到合适的文件
- 显示建议的更改(可以查看和编辑)
- 请求您的批准
- 进行编辑
目的: 熟悉审批流程和权限系统
第3步:使用Git集成(5-10分钟)
> what files have I changed?
> show me the git status
> create a commit with a descriptive message
> create a new branch called feature/my-feature
目的: 学习如何让Claude管理git操作
第4步:修复bugs或添加功能(变长)
> there's a bug where users can submit empty forms - fix it
> add input validation to the registration form
> write unit tests for the calculator functions
> run the tests and fix any failures
目的: 进行完整的功能开发工作流
交互式快捷键
| 快捷键 | 功能 | 平台 |
|---|---|---|
Ctrl+C |
中止当前操作 | 所有 |
? |
显示所有可用的键盘快捷键 | 所有 |
Tab |
命令完成/自动完成 | 所有 |
↑ / ↓ |
命令历史导航 | 所有 |
Ctrl+R |
反向搜索历史 | Unix/Linux/macOS |
Shift+Enter |
多行输入(需要配置) | 所有 |
Shift+Tab |
循环切换权限模式 | 所有 |
Ctrl+O |
切换详细模式(查看thinking过程) | 所有 |
/ |
显示所有斜杠命令 | 所有 |
Escape |
清空当前输入 | 所有 |
常用会话命令
# 列出所有会话
claude --list-sessions
# 获取会话详情
claude --session-info session-name
# 重命名会话
/rename new-session-name
# 删除会话
claude --delete-session session-name
# 清空当前对话历史
/clear
# 压缩对话历史
/compact
# 回退到上一个状态
/rewind
支持的功能
1. 斜杠命令(Slash Commands)
斜杠命令在Claude Code中提供快速访问常用功能。所有命令以/开头。
内置斜杠命令总览
项目和工作流:
| 命令 | 功能 | 用途 |
|---|---|---|
/init |
初始化项目CLAUDE.md | 创建项目初始化模板 |
/add-dir |
添加额外的工作目录 | 扩展上下文范围 |
/memory |
编辑CLAUDE.md记忆文件 | 更新项目信息 |
代理和子系统:
| 命令 | 功能 | 用途 |
|---|---|---|
/agents |
管理自定义AI子代理 | 创建或配置代理 |
/mcp |
管理MCP服务器连接 | 连接外部工具 |
/plugin |
管理Claude Code插件 | 安装或配置插件 |
账户和认证:
| 命令 | 功能 | 用途 |
|---|---|---|
/login |
切换或添加Anthropic账户 | 账户管理 |
/logout |
登出当前账户 | 断开连接 |
/status |
显示版本、模型、账户信息 | 查看当前状态 |
配置和设置:
| 命令 | 功能 | 用途 |
|---|---|---|
/config |
打开设置界面 | 修改全局设置 |
/model |
选择或更改AI模型 | 切换模型 |
/permissions |
查看或更新权限规则 | 管理操作权限 |
/hooks |
管理hook配置 | 配置自动化脚本 |
/sandbox |
启用沙箱bash工具 | 启用隔离执行 |
诊断和帮助:
| 命令 | 功能 | 用途 |
|---|---|---|
/doctor |
检查Claude Code安装健康状态 | 故障排除 |
/help |
获取使用帮助 | 查看文档 |
/bug |
报告bugs(发送到Anthropic) | 反馈问题 |
分析和监控:
| 命令 | 功能 | 用途 |
|---|---|---|
/context |
可视化当前上下文使用 | 监控context大小 |
/cost |
显示token使用统计 | 了解使用成本 |
/stats |
可视化日常使用情况 | 分析使用模式 |
会话管理:
| 命令 | 功能 | 用途 |
|---|---|---|
/resume [session] |
恢复对话或打开选择器 | 继续之前的工作 |
/rewind |
回退对话和/或代码 | 撤销更改 |
/rename |
重命名当前会话 | 组织会话 |
/clear |
清除对话历史 | 开始新对话 |
/compact |
压缩对话 | 减少token使用 |
自定义斜杠命令
在项目中创建自定义命令以自动化常见任务。
基本创建步骤:
# 创建命令目录
mkdir -p .claude/commands
# 创建新命令文件(使用.md或.txt扩展名)
echo "Analyze this code for performance issues and suggest optimizations:" > .claude/commands/optimize.md
# 使用命令
/optimize
带参数的命令:
使用$ARGUMENTS捕获所有参数,或$1、$2等访问特定参数。
# 创建 fix-issue.md
echo 'Fix issue #$ARGUMENTS following our coding standards' > .claude/commands/fix-issue.md
# 使用:
/fix-issue 123
# 创建带多参数的命令 review-pr.md
echo 'Review PR #$1 with priority $2' > .claude/commands/review-pr.md
# 使用:
/review-pr 456 high
个人命令(跨项目):
在用户home目录创建,所有项目都可用:
# 创建个人命令目录
mkdir -p ~/.claude/commands
# 创建命令
echo "Review this code for security vulnerabilities:" > ~/.claude/commands/security-review.md
# 任何项目中都可用
/security-review
命令优先级:
- 项目命令(
.claude/commands/)- 最高优先级 - 个人命令(
~/.claude/commands/)- 次级优先级
2. Hooks(钩子)- 自动化工作流
Hooks允许在Claude Code生命周期的各个点执行自定义shell命令,实现强大的自动化。
Hook事件类型
| 事件 | 触发时机 | 典型用途 |
|---|---|---|
| SessionStart | 会话启动时 | 初始化环境、加载凭证 |
| SessionEnd | 会话结束时 | 清理工作、保存状态 |
| PreToolUse | 工具调用前 | 阻止某些操作、验证 |
| PostToolUse | 工具调用后 | 自动格式化、运行测试、日志记录 |
| PermissionRequest | 权限对话时 | 自动允许/拒绝操作 |
| UserPromptSubmit | 用户提交提示前 | 验证或自动添加上下文 |
| Notification | 发送通知时 | 自定义通知方式 |
| Stop | Claude完成响应时 | 执行清理任务 |
Hook配置方法
方法1:使用/hooks命令
/hooks
交互式配置界面。
方法2:直接编辑配置文件
编辑~/.claude/settings.json或.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '\\'\\(.tool_input.command)\\'' >> ~/.claude/bash-command-log.txt"
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write \"$file_path\""
}
]
}
]
}
}
Hook常见用例
1. 自动代码格式化
在编辑或写入文件后自动运行prettier:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write \"$file_path\""
}
]
}
]
}
}
2. 自动修复linting错误
在文件修改后运行eslint修复:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx eslint --fix \"$file_path\" 2>/dev/null || true"
}
]
}
]
}
}
3. 保护敏感文件
在编辑或写入操作前检查文件路径:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "python3 -c \"import json, sys; data=json.load(sys.stdin); path=data.get('tool_input',{}).get('file_path',''); sys.exit(2 if any(p in path for p in ['.env', '.git/', 'secrets']) else 0)\""
}
]
}
]
}
}
4. 自动运行测试
在修改代码后自动运行相关测试:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npm test 2>&1 | tail -20"
}
]
}
]
}
}
5. 自动提交日志
记录所有bash命令用于审计:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo \"[$(date)] User: $(whoami) Command: $(<stdin)\" >> ~/.claude/command-audit.log"
}
]
}
]
}
}
6. 系统通知
当Claude完成操作时发送系统通知:
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "notify-send 'Claude Code' 'Task completed, awaiting your input'"
}
]
}
]
}
}
3. MCP(Model Context Protocol)- 连接外部工具
MCP是一个开源标准,允许Claude Code连接到数百个外部工具和数据源,大幅扩展功能。
流行的MCP服务器
| 服务 | 功能 | 用途 |
|---|---|---|
| GitHub | 代码审查、PR管理、问题跟踪 | 管理开发工作流 |
| Sentry | 错误监控和调试 | 监控应用问题 |
| PostgreSQL | 数据库查询和管理 | 访问数据库 |
| Notion | 文档和笔记 | 访问团队文档 |
| Airtable | 数据库和表格 | 管理数据 |
| Slack | 消息和通知 | 团队沟通 |
| Google Drive | 文档访问 | 访问共享文档 |
| Figma | 设计文件 | 查看设计资源 |
安装MCP服务器
HTTP服务器:
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
SSE(Server-Sent Events)服务器:
claude mcp add --transport sse asana https://mcp.asana.com/sse
Stdio服务器(本地可执行文件):
claude mcp add --transport stdio airtable --env AIRTABLE_API_KEY=YOUR_KEY -- npx -y airtable-mcp-server
管理MCP服务器
# 列出所有配置的服务器
claude mcp list
# 获取特定服务器的详细信息
claude mcp get github
# 删除服务器
claude mcp remove github
# 在Claude Code会话中查看和管理
/mcp
使用MCP服务器
连接后,在Claude Code会话中自然查询:
> "What are the most common errors in the last 24 hours?" (Sentry)
> "Show me all open PRs assigned to me" (GitHub)
> "What's our total revenue this month?" (数据库查询)
> "Find all TODO items in our engineering docs" (Notion)
> "What designs are pending review in Figma?" (Figma)
4. 子代理(Subagents)- 专门的AI助手
子代理是专门化的AI助手,可以自动化处理特定的复杂任务。
内置子代理
- Plan subagent - 用于安全代码分析和规划
查看和创建子代理
/agents
创建自定义子代理
在.claude/agents/目录创建Markdown文件,使用YAML前置元数据:
---
description: Code reviewer for security analysis
tools: ["Read", "Grep", "Glob"]
model: "claude-3-5-sonnet-20241022"
---
# Security Code Reviewer
You are a senior code security reviewer. Your role is to analyze code for:
- Security vulnerabilities (SQL injection, XSS, CSRF, etc.)
- Authentication and authorization issues
- Data protection and privacy concerns
- Cryptography best practices
- API security issues
When reviewing code:
1. Identify all potential vulnerabilities
2. Explain the risk level for each
3. Suggest specific fixes with code examples
4. Recommend additional security measures
使用自定义子代理:
/code-security-reviewer
5. 插件(Plugins)- 扩展功能
插件是打包的扩展,可以包含:
- 自定义命令
- 子代理
- Skills
- Hooks
- MCP服务器
管理插件
/plugin
交互式浏览和安装来自marketplaces的插件。
6. Skills(技能)- 可重用能力
Skills是可重用的工作流和配置集合,包含多个文件和相关设置。
创建Skill
在.claude/skills/my-skill/目录创建:
目录结构:
.claude/skills/code-reviewer/
├── SKILL.md # Skill描述和文档
├── setup.sh # 设置脚本(可选)
├── requirements.txt # 依赖(可选)
└── examples.md # 使用示例(可选)
SKILL.md 模板:
# Code Review Skill
这个Skill帮助进行全面的代码审查和质量检查。
## 功能
- 安全漏洞分析
- 代码质量检查
- 性能优化建议
- 最佳实践验证
## 使用场景
当您想要:
- 审查代码质量
- 检查安全问题
- 验证性能
- 确保符合规范
使用这个Skill。
## 示例
### 安全审查
use code-reviewer skill to check for vulnerabilities
### 性能分析
use code-reviewer skill to suggest performance improvements
## 依赖
- Node.js 16+
- npm
配置方式
配置文件位置和作用域
Claude Code使用作用域系统来确定配置位置和共享范围。
配置层级
| 作用域 | 位置 | 影响范围 | 共享 | 优先级 |
|---|---|---|---|---|
| 企业 | 系统级managed-settings.json |
所有用户 | IT部署 | 1(最高) |
| 命令行 | 参数 | 当前会话 | 临时 | 2 |
| 本地 | .claude/settings.local.json |
仅您,此项目 | 否(gitignore) | 3 |
| 项目 | .claude/settings.json |
项目所有协作者 | 是(git) | 4 |
| 用户 | ~/.claude/settings.json |
您,所有项目 | 否 | 5(最低) |
优先级规则: 从上到下,高优先级覆盖低优先级的设置。企业设置最高,无法被本地覆盖。
settings.json 配置详解
完整配置模板
{
"env": {
"HTTP_PROXY": "http://127.0.0.1:7897",
"HTTPS_PROXY": "http://127.0.0.1:7897",
"NO_PROXY": "localhost,127.0.0.1",
"CLAUDE_CODE_MAX_OUTPUT_TOKENS": "32000",
"BASH_DEFAULT_TIMEOUT_MS": "600000",
"MCP_TIMEOUT": "30000"
},
"model": "sonnet",
"outputStyle": "Explanatory",
"permissions": {
"mode": "ask",
"allow": [
"Bash(npm run lint:*)",
"Bash(npm run test:*)",
"Read(~/.zshrc)",
"Edit",
"Glob",
"Grep",
"WebFetch"
],
"deny": [
"Bash(curl:*)",
"Bash(ssh:*)",
"Bash(sudo:*)",
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)",
"WebFetch(https://sensitive-api.com/**)"
]
},
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write \"$file_path\""
}
]
}
]
},
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": true,
"excludedCommands": ["git", "docker"]
},
"attribution": {
"commit": "Generated with Claude Code"
},
"statusLine": {
"type": "command",
"command": "echo 'Claude Code: Ready'"
}
}
配置项详解
| 键 | 类型 | 描述 | 默认值 | 示例 |
|---|---|---|---|---|
env |
对象 | 环境变量 | {} |
{"FOO": "bar"} |
model |
字符串 | 默认模型 | "sonnet" |
"claude-opus-4-5-20251101" |
outputStyle |
字符串 | 输出风格 | "Explanatory" |
"Concise" |
permissions.mode |
字符串 | 权限模式 | "ask" |
"acceptEdits" |
permissions.allow |
数组 | 允许的工具 | [] |
["Bash", "Edit"] |
permissions.deny |
数组 | 拒绝的工具 | [] |
["WebFetch"] |
hooks |
对象 | Hook配置 | {} |
见Hook部分 |
sandbox.enabled |
布尔 | 启用沙箱 | false |
true |
attribution.commit |
字符串 | Git署名 | "" |
"Generated with Claude Code" |
环境变量配置
关键环境变量可在settings.json的env字段设置:
{
"env": {
"ANTHROPIC_AUTH_TOKEN": "sk-...",
"ANTHROPIC_BASE_URL": "https://api.anthropic.com",
"HTTP_PROXY": "http://proxy:port",
"HTTPS_PROXY": "http://proxy:port",
"NO_PROXY": "localhost,127.0.0.1",
"CLAUDE_CODE_MAX_OUTPUT_TOKENS": "32000",
"BASH_DEFAULT_TIMEOUT_MS": "600000",
"MCP_TIMEOUT": "30000",
"CUSTOM_VAR": "value"
}
}
重要变量说明:
ANTHROPIC_AUTH_TOKEN- API认证令牌ANTHROPIC_BASE_URL- 自定义API端点(企业部署)HTTP_PROXY/HTTPS_PROXY- 代理设置CLAUDE_CODE_MAX_OUTPUT_TOKENS- 最大输出token数BASH_DEFAULT_TIMEOUT_MS- Bash命令超时(毫秒)MCP_TIMEOUT- MCP操作超时(秒)
权限管理详解
权限模式
| 模式 | 行为 | 用途 |
|---|---|---|
ask |
每个操作前询问 | 默认,最安全 |
acceptEdits |
自动接受编辑,其他操作前询问 | 加快编辑工作流 |
plan |
只读分析,无编辑权限 | 安全审查和规划 |
bypassPermissions |
跳过所有权限提示 | 开发环境中使用 |
切换模式:
# 在会话中
Shift+Tab # 循环切换模式
# 在配置中
/config
权限规则语法
{
"permissions": {
"allow": [
"Bash(git diff:*)", # 允许git diff命令
"Bash(npm run build:*)", # 允许npm run build:*
"Bash(npm run test:*)", # 允许npm run test:*
"Read(/path/to/file)", # 允许读取文件
"Read(/path/to/dir/**)", # 允许读取目录
"Edit(/path/to/dir/**)", # 允许编辑目录下文件
"Glob", # 允许文件搜索
"Grep", # 允许内容搜索
"WebFetch", # 允许网页获取
"SlashCommand:/review-pr:*" # 允许自定义命令
],
"deny": [
"Bash(curl:*)", # 拒绝curl
"Bash(ssh:*)", # 拒绝ssh
"Bash(sudo:*)", # 拒绝sudo
"Read(./.env)", # 拒绝读取.env
"Read(./.env.*)", # 拒绝读取所有.env文件
"Read(./secrets/**)", # 拒绝读取secrets目录
"WebFetch(https://sensitive-api.com/**)", # 拒绝访问敏感API
"Edit(./production/**)" # 拒绝编辑生产代码
]
}
}
规则应用顺序:
- 首先检查
deny列表 - 然后检查
allow列表 - 如果都未匹配,根据模式决定
CLAUDE.md - 项目记忆文件
创建CLAUDE.md或.claude/CLAUDE.md来存储项目特定信息。Claude会在每个会话中读取此文件。
完整模板:
# Project Name
## Overview
本项目是一个[描述],目的是[目的]。主要为[用户/系统]提供[功能]。
## Architecture
### 高层架构
[ASCII图或简述]
### 主要组件
- **Frontend**: React 18 + Redux
- **Backend**: Node.js + Express
- **Database**: PostgreSQL 14
- **Cache**: Redis
- **Message Queue**: RabbitMQ
### 数据流
1. 用户通过前端发起请求
2. 请求发送到API服务器
3. 服务器查询数据库
4. 返回结果给前端
## Tech Stack
### Frontend
- React 18
- Redux Toolkit
- TypeScript
- Tailwind CSS
- Jest + React Testing Library
### Backend
- Node.js 18+
- Express.js
- TypeScript
- PostgreSQL
- Prisma ORM
- Jest
### DevOps
- Docker + Docker Compose
- GitHub Actions
- AWS EC2 / RDS
## Key Directories
. ├── src/ │ ├── components/ # React组件 │ ├── pages/ # 页面组件 │ ├── utils/ # 工具函数 │ ├── hooks/ # 自定义hooks │ ├── services/ # API服务 │ └── types/ # TypeScript类型 ├── tests/ # 测试文件 ├── public/ # 静态资源 ├── docs/ # 文档 └── docker/ # Docker配置
## Development Guidelines
### 命名约定
- 文件: kebab-case (my-file.ts)
- 文件夹: kebab-case (my-folder)
- 类/接口: PascalCase (MyClass)
- 变量/函数: camelCase (myVariable)
- 常量: UPPER_SNAKE_CASE (MY_CONSTANT)
### 代码风格
- 使用ESLint和Prettier
- 2个空格缩进
- 最大行长度: 100个字符
- TypeScript strict模式
### 测试要求
- 最小覆盖率: 80%
- 单元测试: jest
- 集成测试: jest + supertest
- E2E测试: Cypress
### Git Commit规范
使用Conventional Commits:
feat(auth): add OAuth login fix(api): resolve timeout issue docs(readme): update installation steps
### 代码审查
- 所有PR需要至少2个approval
- 必须通过CI/CD检查
- 必须有相关的测试
- 需要更新相关文档
## Common Tasks
### 安装依赖
```bash
npm install
启动开发服务器
npm run dev
运行测试
npm test # 所有测试
npm test:watch # 监听模式
npm test:coverage # 覆盖率报告
构建
npm run build # 生产构建
npm run build:dev # 开发构建
Linting和格式化
npm run lint # 检查风格
npm run lint:fix # 修复风格问题
npm run format # 格式化代码
数据库迁移
npm run db:migrate # 执行迁移
npm run db:generate # 生成Prisma客户端
npm run db:reset # 重置数据库
Docker相关
docker-compose up # 启动所有服务
docker-compose down # 停止所有服务
docker-compose build # 构建镜像
Important Notes
当前限制
- 暂不支持实时协作
- 最大文件大小: 50MB
- 数据库连接池大小: 20
已知问题
- WebSocket连接在某些网络环境下不稳定
- 大文件上传可能超时
- 某些浏览器不支持特定功能
特殊配置
- 生产环境使用
.env.production - 开发环境使用
.env.development - 测试环境使用
.env.test
认证信息
- JWT_SECRET: [secured]
- API_KEY: [secured]
- 数据库密码: [secured] (敏感信息不应包含在此文件中)
联系方式
- 技术负责人: team@example.com
- 文档: https://docs.example.com
- Bug报告: https://github.com/org/repo/issues
常见问题
Q: 如何添加新的环境变量?
A: 1. 在.env.example中添加
2. 在src/config/env.ts中定义类型
3. 在启动脚本中验证
Q: 如何运行特定的测试?
A: npm test -- --testNamePattern="pattern"
Q: 如何调试应用?
A: 使用VS Code debugger或node --inspect
### 模型配置
```bash
# 查看可用模型
/model
# 设置模型(当前会话)
/model sonnet
# 设置默认模型
# 编辑 ~/.claude/settings.json
# "model": "claude-opus-4-5-20251101"
模型别名和能力:
| 别名 | 完整名称 | 速度 | 智能 | 推荐用途 |
|---|---|---|---|---|
haiku |
Claude Haiku | 快 | 中等 | 快速任务、简单查询 |
sonnet |
Claude Sonnet | 平衡 | 强 | 日常使用、代码编辑 |
opus |
Claude Opus | 慢 | 最强 | 复杂分析、长期项目 |
opusplan |
Opus with Plan | 较慢 | 最强 | 安全分析、规划模式 |
IDE集成
VS Code集成
安装步骤
-
打开Extensions(扩展)
- Mac:
Cmd+Shift+X - Windows/Linux:
Ctrl+Shift+X
- Mac:
-
搜索"Claude Code"
-
点击Install安装
-
重启VS Code(可能需要)
直接安装链接:
vscode:extension/anthropic.claude-code
VS Code中使用Claude Code
打开Claude Code的方式:
- 点击编辑器右上角的Spark(✨)图标
- 点击状态栏右侧的"✱ Claude Code"按钮
- 打开命令面板:
Cmd+Shift+P/Ctrl+Shift+P,搜索"Claude Code"
VS Code快捷键:
| 命令 | Mac | Windows/Linux |
|---|---|---|
| Focus Claude Code输入 | Cmd+Esc |
Ctrl+Esc |
| 新Tab | Cmd+Shift+Esc |
Ctrl+Shift+Esc |
| 插入@提及 | Alt+K |
Alt+K |
| 新对话 | Cmd+N |
Ctrl+N |
| 发送消息 | Cmd+Enter / Ctrl+Enter |
Ctrl+Enter |
VS Code设置
打开设置: Cmd+, (Mac) 或 Ctrl+, (Windows/Linux)
导航到: Extensions → Claude Code
常用设置项:
| 设置 | 说明 | 选项 |
|---|---|---|
| Selected Model | 默认使用的模型 | haiku, sonnet, opus |
| Use Terminal | 使用终端模式 | true/false |
| Initial Permission Mode | 初始权限模式 | ask, acceptEdits, plan |
| Preferred Location | Claude Code面板位置 | sidebar, tab, panel |
| Autosave | 自动保存修改 | true/false |
| Use Ctrl+Enter to Send | 用Ctrl/Cmd+Enter发送 | true/false |
| Respect Git Ignore | 遵守.gitignore | true/false |
| Show Token Count | 显示token计数 | true/false |
VS Code Extension vs CLI比较
| 功能 | VS Code扩展 | CLI |
|---|---|---|
| 交互式编辑 | ✓ | ✓ |
| 斜杠命令 | 子集 | 完整 |
| MCP配置 | ✗ | ✓ |
| 检查点/会话恢复 | 即将推出 | ✓ |
| 最大上下文 | 支持 | 支持 |
| 文件编辑 | 集成编辑器 | 直接修改 |
| 集成VS Code功能 | ✓ | ✗ |
JetBrains IDE集成(IntelliJ, PyCharm等)
安装步骤
-
打开Plugins管理器
- 菜单: Preferences → Plugins(Mac)
- 菜单: Settings → Plugins(Windows/Linux)
-
搜索"Claude Code"插件
-
点击Install安装
-
重启IDE
JetBrains中使用
- 在JetBrains的Terminal(终端)运行
claude - IDE会自动检测并集成
- 在Claude Code会话中使用
/ide连接IDE - 支持右键菜单快速操作
JetBrains配置
Settings → Tools → Terminal:
- 配置Claude Code路径
- 设置快捷键
- 配置环境变量
WSL2上的JetBrains集成
如果在WSL2中运行JetBrains,可能需要配置Windows防火墙。
推荐方案:启用镜像网络
# ~/.wslconfig
[wsl2]
networkingMode=mirrored
或配置防火墙规则:
# 以管理员身份运行PowerShell
# 获取WSL2 IP
wsl hostname -I
# 创建防火墙规则
New-NetFirewallRule `
-DisplayName "Allow WSL2 IDE" `
-Direction Inbound `
-Protocol TCP `
-Action Allow `
-RemoteAddress 172.21.0.0/16 `
-LocalAddress 172.21.0.0/16
常用场景和最佳实践
场景1:快速理解新代码库(初期入职)
目标: 快速掌握项目结构和关键概念
步骤:
cd /path/to/project
claude
# 阶段1:整体了解
> give me a high-level overview of this codebase
> what is the main purpose of this project?
> what technologies and frameworks are used?
> explain the overall architecture and component relationships
# 阶段2:细节了解
> what are the key data models and their relationships?
> how is user authentication and authorization implemented?
> what are the main API endpoints and what do they do?
# 阶段3:开发信息
> what are the main coding patterns and conventions used here?
> how do you run tests and build the project?
> what are the deployment processes?
预期输出:
- 项目用途和主要功能
- 技术栈详情
- 架构图或描述
- 关键文件和目录说明
- 数据模型详解
- API端点文档
最佳实践:
- 从宽泛问题开始,逐步深入具体区域
- 要求提供架构图或流程图
- 询问编码约定和使用的设计模式
- 要求项目特定术语的术语表
- 保存重要信息到CLAUDE.md
场景2:修复Bug(问题解决)
目标: 高效地识别和修复bug
步骤:
# 描述问题
> I'm seeing a blank screen error when I run the login flow
# 提供重现步骤
> Here's how to reproduce it:
> 1. Go to /login
> 2. Enter wrong credentials
> 3. Click submit
> The page goes blank instead of showing an error message
# 要求分析
> analyze the login component and API error handling
> what could be causing the blank screen?
> suggest a few ways to fix this issue
# 应用修复
> @src/components/Login.tsx update to add proper error handling as you suggested
# 验证修复
> run the test suite to make sure the fix doesn't break anything
> let's test the login flow manually
最佳实践:
- 清楚地描述bug症状和重现步骤
- 粘贴完整的错误消息和stack trace
- 指出是间歇性还是一致出现
- 要求Claude先分析问题原因
- 在应用修复后运行相关测试
- 考虑添加测试用例防止回归
场景3:代码重构
目标: 改进代码质量和可维护性
步骤:
# 分析当前代码
> analyze @src/utils/helpers.ts for code quality issues
# 识别改进机会
> what modern JavaScript features could improve this code?
> suggest a refactoring plan
# 制定重构计划
> let's refactor utils.js step by step to use modern ES2024 features while maintaining backward compatibility
# 分步实施
> create a new version of the utility functions using destructuring and async/await
# 测试验证
> run the test suite for the refactored code
# 处理边界情况
> add handling for edge cases like null values and empty arrays
# 最后验证
> run the full test suite one more time to ensure everything works
最佳实践:
- 重构前让Claude解释现代方法的优势
- 分小步进行重构和测试
- 保留向后兼容性(如需要)
- 运行全面测试套件
- 更新相关文档
场景4:编写测试
目标: 提高代码测试覆盖率
步骤:
# 分析覆盖率
> find functions in @src/services/NotificationService.ts that don't have test coverage
# 理解现有测试
> show me the structure of existing tests in the test directory
# 创建测试
> write comprehensive unit tests for the NotificationService
# 覆盖边界情况
> add test cases for these edge conditions:
> - Null or undefined inputs
> - Empty arrays
> - API timeout scenarios
> - Permission denied errors
# 运行测试
> run the new tests and show me the results
# 修复失败的测试
> the test failed with this error: [paste error]. Fix the test.
最佳实践:
- Claude会检查现有测试文件以匹配风格
- 要求覆盖happy path和边界情况
- 包括错误和异常情况
- 运行并验证覆盖率报告
- 保持测试的可读性和维护性
场景5:创建Pull Request
目标: 高效地创建和提交PR
步骤:
# 查看变更
> what files have I changed in this session?
> show me a summary of all changes
# 创建分支(如需要)
> create a new branch called feature/user-dashboard
# 制作提交消息
> write a clear commit message following conventional commits format
# 创建PR
> create a pull request with a detailed description
# 增强PR描述
> enhance the PR description with:
> - What changed and why
> - How to test the changes
> - Any breaking changes or migration steps needed
# 验证PR
> verify that all checks pass
预期的PR包括:
- 清晰的标题和描述
- 相关的issue链接
- 测试计划
- 截图或视频(UI变更)
- 迁移说明(如适用)
最佳实践:
- 一个PR处理一个功能或bug
- 保持PR大小合理(便于审查)
- 提供清晰的提交历史
- 更新相关文档
- 要求CI/CD检查通过
场景6:使用Plan Mode(安全分析)
目标: 在不修改代码的情况下进行分析和规划
启动Plan Mode:
# 方式1:启动时使用Plan Mode
claude --permission-mode plan
# 方式2:在会话中切换
Shift+Tab # 循环切换权限模式,直到到达plan模式
Plan Mode特点:
- 完全只读,无编辑权限
- 支持所有分析工具
- 安全的交互式开发
- 多步骤实现前的规划
使用场景:
# 在Plan Mode中
> analyze the performance bottlenecks in this application
> design a caching strategy for our API
> propose a refactoring plan for the authentication module
> identify security vulnerabilities in the code
优势:
- 获得建议而无需修改代码
- 审查和评估变更影响
- 团队讨论前进行分析
- 确定是否需要大规模重构
最佳实践总结
1. 具体化请求
❌ 不好: "fix the bug"
✓ 好: "fix the login bug where users see a blank screen after entering wrong credentials instead of showing the error message"
2. 使用@提及文件
> Explain the logic in @src/utils/auth.js
> Compare @src/old-version.js with @src/new-version.js
> Fix the bug in @src/api/user.ts
3. 分步式指令
> 1. Create a new database table for user profiles
> 2. Create an API endpoint to GET and UPDATE user profiles
> 3. Build a React page that allows users to view and edit their information
> 4. Write tests for the new functionality
> 5. Create a migration script
4. 让Claude先探索
> Analyze the database schema and understand relationships
> Look at how similar features are implemented
> Then suggest improvements and optimizations
5. 使用扩展思考
> ultrathink: design a comprehensive caching layer for our API that handles:
> - Request deduplication
> - Cache invalidation
> - TTL management
> - Memory efficiency
# 或全局启用
/config # 切换thinking mode on
6. 管理上下文
# 定期压缩对话以减少token使用
/compact
# 查看当前context使用情况
/context
# 查看token成本
/cost
# 重新开始新对话
/clear
7. 验证结果
> run the tests to verify the changes work
> build the project and show me any warnings or errors
> check the app manually by [description of steps]
8. 处理错误
> The test failed with this error: [error message]
> The build shows this warning: [warning text]
> This API call returns: [actual vs expected]
故障排除和常见问题
安装问题
Windows WSL中的错误
问题1:OS检测错误
# 解决方案
npm config set os linux
npm install -g @anthropic-ai/claude-code --force --no-os-check
问题2:Node/npm未找到
# 检查Node路径
which npm
which node
# 应该指向/usr/路径,不是/mnt/c/
# 如果不正确,更新PATH变量
问题3:nvm版本冲突
# 确保nvm在shell初始化文件中加载
# 编辑 ~/.bashrc 或 ~/.zshrc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
# 在当前会话中应用
source ~/.nvm/nvm.sh
Linux/Mac权限错误
推荐:使用官方安装脚本
curl -fsSL https://claude.ai/install.sh | bash
如果仍有问题:
# 清除npm缓存
npm cache clean --force
# 重新安装
npm install -g @anthropic-ai/claude-code
权限和认证问题
重复权限提示
使用/permissions允许特定工具运行而无需重复批准:
/permissions
# 在允许列表中添加
Bash(npm run lint:*)
Bash(npm run test:*)
Edit
Glob
Grep
认证失效
# 完全登出
/logout
# 关闭Claude Code终端窗口
# 重新启动
claude
# 如果问题持续
rm -rf ~/.config/claude-code/auth.json
rm -rf ~/.claude/auth.json
# 重新启动
claude
账户切换
# 登出当前账户
/logout
# 登入不同账户
/login
# 或在命令行
claude --account different-account@example.com
性能问题
高CPU或内存使用
# 压缩对话历史
/compact
# 查看context大小
/context
# 关闭并重启Claude Code
# 在settings.json中增加较大目录到忽略列表
# 编辑 ~/.claude/settings.json 或 .claude/settings.json
优化配置:
{
"env": {
"CLAUDE_CODE_MAX_OUTPUT_TOKENS": "16000",
"BASH_DEFAULT_TIMEOUT_MS": "60000"
},
"permissions": {
"deny": [
"Read(node_modules/**)",
"Read(.git/**)",
"Read(dist/**)",
"Read(build/**)"
]
}
}
命令挂起或超时
# 中止当前操作
Ctrl+C
# 如果无响应,关闭终端窗口并重启
# 增加超时时间
# 在 ~/.claude/settings.json
{
"env": {
"BASH_DEFAULT_TIMEOUT_MS": "600000",
"MCP_TIMEOUT": "60"
}
}
WSL搜索性能慢
# 使用更具体的搜索而不是全局搜索
> Search for JWT validation logic in the auth-service package
> Find all uses of md5 hash in JavaScript files
# 对于大型项目,将项目移到Linux文件系统
# /home/ 而不是 /mnt/c/
IDE集成问题
VS Code中Escape键不工作
编辑 settings.json(命令面板: Ctrl+Shift+P > “Preferences: Open Settings (JSON)"):
{
"keybindings": [
{
"key": "escape",
"command": "-workbench.action.closeQuickOpen"
}
]
}
JetBrains IDE在WSL2上未检测到Claude Code
选项1:配置防火墙(推荐)
# 找到WSL2 IP
wsl hostname -I # 例如: 172.21.0.1
# 在Windows PowerShell中(以管理员身份)
New-NetFirewallRule -DisplayName "Allow WSL2" `
-Direction Inbound `
-Protocol TCP `
-Action Allow `
-RemoteAddress 172.21.0.0/16 `
-LocalAddress 172.21.0.0/16
选项2:启用镜像网络(需要Windows 11)
# ~/.wslconfig
[wsl2]
networkingMode=mirrored
VS Code Claude Code扩展无法启动
# 卸载扩展
# 在VS Code中打开命令面板:Cmd+Shift+P / Ctrl+Shift+P
# 搜索 "Extensions: Uninstall Extension"
# 选择 Claude Code
# 重新安装
# 搜索 Claude Code 并重新安装
# 重启VS Code
常见错误信息
“Claude not responding” / 连接错误
# 1. 检查网络连接
ping google.com
# 2. 启动新对话(旧会话可能有问题)
claude
/clear
# 3. 尝试CLI验证(更详细的错误信息)
claude doctor
# 4. 检查配置
/status
# 5. 重新登录
/logout
/login
搜索不工作(Grep/Glob失败)
# 在Linux上,如果没有ripgrep
brew install ripgrep # macOS
sudo apt install ripgrep # Ubuntu/Debian
# 然后设置
export USE_BUILTIN_RIPGREP=0
Markdown格式问题
> Fix spacing and formatting issues in this markdown file
> Make sure all code blocks have appropriate language tags
> Fix inconsistent heading levels and indentation
Claude Code无法编辑文件
检查权限:
# 查看权限规则
/permissions
# 确保文件不在deny列表中
# 添加到allow列表
Edit
检查文件状态:
# 确保文件不被其他程序锁定
lsof /path/to/file # macOS/Linux
获取帮助和支持
1. 在Claude Code中报告Bug
/bug
会打开bug报告表单,发送给Anthropic官方。
2. 检查GitHub问题和讨论
https://github.com/anthropics/claude-code/issues
- 搜索您的问题
- 查看已报告的bug
- 参与讨论
3. 运行诊断
/doctor
输出系统和安装信息,帮助调试问题。
4. 查看日志
# 查看Claude Code日志
tail -f ~/.claude/logs/claude.log
# 或在macOS
log stream --predicate 'process == "claude"'
5. 询问Claude其能力
> what are the limitations of Claude Code?
> how do I use MCP with Claude Code?
> how do I create custom commands?
> how do I configure Claude Code for corporate networks?
> what privacy and security features does Claude Code have?
高级功能
1. 扩展思考(Extended Thinking)
启用扩展思考用于复杂的推理任务,Claude会在提供答案前进行深入思考。
启用扩展思考
全局启用:
/config
# 找到 "Enable Thinking Mode" 或 "Thinking"
# 启用并保存
单个请求:
> ultrathink: design a caching layer for our API that handles:
> - Request deduplication
> - Cache invalidation
> - TTL management
> - Memory efficiency
查看思考过程
# 进入详细模式
Ctrl+O
# 或设置
/config
# 启用 "Show Extended Thinking" 或 "Verbose Output"
配置思考token数量
编辑~/.claude/settings.json:
{
"env": {
"MAX_THINKING_TOKENS": "10000"
}
}
2. 会话恢复和检查点
Claude Code支持会话保存和恢复,让您可以中断工作后继续。
会话管理
# 继续最近的会话
claude --continue
# 或
claude -c
# 恢复特定会话
claude --resume auth-refactor
# 或在交互式选择器中选择
claude --resume
# 列出所有会话
claude --list-sessions
# 获取会话详情
claude --session-info session-name
# 重命名会话
/rename new-name
# 删除会话
claude --delete-session session-name
检查点(Checkpoints)
手动创建代码检查点:
# 当前仅在CLI中可用
# 在会话中,Claude自动保存状态
会话持久化
会话自动保存到~/.claude/sessions/目录,包括:
- 对话历史
- 代码变更
- 模型配置
- 权限状态
3. 云端执行(Claude Code on the Web)
在web浏览器中运行Claude Code。
特点:
- 异步任务执行
- 云环境和依赖预装
- 网络访问和安全策略
- 多会话支持
使用场景:
- 快速原型开发
- 没有本地环境时
- 团队协作演示
- 在线教学
4. CI/CD集成
在GitHub Actions等CI/CD流程中使用Claude Code。
GitHub Actions示例
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
claude-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Review PR with Claude Code
uses: anthropics/claude-code@main
with:
args: "--permission-mode plan -p 'Review this PR for security, performance, and best practices'"
api-key: ${{ secrets.ANTHROPIC_API_KEY }}
- name: Security Scan
uses: anthropics/claude-code@main
with:
args: "-p 'Scan for security vulnerabilities and suggest fixes'"
api-key: ${{ secrets.ANTHROPIC_API_KEY }}
其他CI/CD流程
类似地集成到GitLab CI、Jenkins、CircleCI等:
# GitLab CI
script:
- claude -p "Review code for issues"
# Jenkins
sh 'claude -p "Build and test the project"'
# 通用
curl -X POST ... | claude -p "Process and analyze"
5. 沙箱执行
启用沙箱隔离bash命令,增强安全性。
配置沙箱
编辑~/.claude/settings.json:
{
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": true,
"timeoutMs": 300000,
"excludedCommands": [
"git",
"docker",
"sudo",
"ssh"
]
}
}
沙箱特性
- 隔离的文件系统
- 限制网络访问
- 资源限制
- 命令白名单/黑名单
- 环境隔离
何时使用沙箱
- 运行不受信任的代码
- 测试潜在危险的操作
- 学习环境
- 共享机器
关键资源和参考
官方文档
| 资源 | URL | 内容 |
|---|---|---|
| 完整文档 | https://code.claude.com/docs/en/ | 所有官方文档 |
| CLI参考 | https://code.claude.com/docs/en/cli-reference.md | 所有命令详解 |
| 常见工作流 | https://code.claude.com/docs/en/common-workflows.md | 使用场景示例 |
| MCP指南 | https://code.claude.com/docs/en/mcp.md | MCP集成指南 |
| Hooks指南 | https://code.claude.com/docs/en/hooks-guide.md | Hook配置和示例 |
| 设置参考 | https://code.claude.com/docs/en/settings.md | 配置文件详解 |
| IAM和权限 | https://code.claude.com/docs/en/iam.md | 权限管理系统 |
| 故障排除 | https://code.claude.com/docs/en/troubleshooting.md | 问题解决指南 |
GitHub仓库
- Claude Code: https://github.com/anthropics/claude-code
- Issue Tracker: https://github.com/anthropics/claude-code/issues
- Discussions: https://github.com/anthropics/claude-code/discussions
社区资源
- 官方Discord: https://discord.gg/anthropic
- Stack Overflow: 搜索
claude-code标签 - Twitter/X: @anthropicai
学习资源
- 官方教程: https://code.claude.com/docs/en/tutorials/
- 示例项目: https://github.com/anthropics/claude-code-examples
- 最佳实践: https://code.claude.com/docs/en/best-practices.md
进一步学习
Agent SDK
使用TypeScript或Python构建自定义代理:
- 文档: https://sdk.claude.com/
- GitHub: https://github.com/anthropics/anthropic-sdk-python
- 示例: https://github.com/anthropics/anthropic-sdk-python/tree/main/examples
Claude API
直接使用Claude API的应用开发:
企业部署
- AWS Bedrock 集成: https://docs.aws.amazon.com/bedrock/
- Google Vertex AI: https://cloud.google.com/vertex-ai/
- 自托管LLM Gateway
总结
Claude Code是一个强大且灵活的开发工具,具有以下关键特点:
核心优势
| 优势 | 说明 |
|---|---|
| 易于使用 | 简单的命令行界面,快速上手 |
| 功能强大 | 支持多种开发任务自动化 |
| 高度灵活 | Hooks、插件、自定义命令等扩展 |
| 可扩展 | MCP集成、子代理、Skills等 |
| 安全可靠 | 细粒度权限控制、沙箱隔离、企业配置 |
| 高效协作 | 支持团队配置、会话共享、文档集成 |
主要用途
- 代码理解 - 快速掌握新代码库
- Bug修复 - 高效地识别和解决问题
- 功能开发 - 加速新功能实现
- 代码审查 - 自动化代码质量检查
- 任务自动化 - 自动化重复工作
- 文档生成 - 生成更新和文档
成功的关键
- 熟悉基本命令 - 掌握核心工作流
- 充分利用配置 - 定制适合团队的设置
- 遵循最佳实践 - 使用正确的提示技巧
- 持续学习 - 探索新功能和集成
- 社区参与 - 从社区获取建议和支持
快速开始检查清单
- 安装Claude Code
- 配置基本设置(模型、权限)
- 创建CLAUDE.md项目文档
- 配置MCP服务(如需)
- 设置Hooks自动化(如需)
- 学习常用快捷键
- 在小项目上练习
- 配置VS Code或JetBrains集成
- 定制斜杠命令
- 建立团队规范和最佳实践
下一步
- 阅读官方文档 - 深入了解具体功能
- 尝试MCP集成 - 连接您常用的工具
- 创建自定义工具 - 编写Hooks和命令
- 参与社区 - 分享经验和获取帮助
- 优化工作流 - 根据使用经验不断改进
祝您使用Claude Code愉快!如有任何问题,不要犹豫访问官方文档或GitHub讨论。