首页 AI系列88:Claude Code入门
文章
取消

AI系列88:Claude Code入门

Claude Code使用

登录

一种是使用官方订阅 一种是通过Anthropic Console account

升级

claude -v claude update https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md

最好用纯英文 tail -f app.log | claude -p “Slack me if you see any anomalies appear in this log stream” Your CI can run claude -p “If there are new text strings, translate them into French and raise a PR for @lang-fr-team to review”. //注 claude -p “query” 运行一次性查询,然后退出 输入 /resume 继续之前的对话

常用提示词

what does this project do? what technologies does this project use? where is the main entry point? explain the folder structure

add a hello world function to the main file

git使用

Claude Code 可以使 Git 操作变得对话式: what files have I changed? commit my changes with a descriptive message create a new branch called feature/quickstart show me the last 5 commits help me resolve merge conflicts

修复错误或添加功能

add input validation to the user registration form there’s a bug where users can submit empty forms - fix it

refactor the authentication module to use async/await instead of callbacks write unit tests for the calculator functions 更新文档:update the README with installation instructions review my changes and suggest improvements

常用命令

claude -c 继续最近的对话 claude -r 恢复之前的对话 claude commit 创建 Git 提交 按 ↑ 查看命令历史

使用建议

1,问题要具体 2,拆分为多步

常见工作流程

示例

理解新代码库

give me an overview of this codebase 了解特定组件 explain the main architecture patterns used here what are the key data models? how is authentication handled? 查找代码:find the files that handle user authentication how do these authentication files work together? 理解执行流程trace the login process from front-end to database

修复错误

I’m seeing an error when I run npm test uggest a few ways to fix the @ts-ignore in user.ts update user.ts to add the null check you suggested

重构代码

find deprecated API usage in our codebase suggest how to refactor utils.js to use modern JavaScript features

refactor utils.js to use ES2024 features while maintaining the same behavior

使用专门的子代理

use the code-reviewer subagent to check the auth module

使用计划模式

适合探索代码库,规划复杂更改 按Shift+Tab 进入 claude –permission-mode plan claude –permission-mode plan -p “Analyze the authentication system and suggest improvements” I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.

测试

识别未测试的代码 > find functions in NotificationsService.swift that are not covered by tests add tests for the notification service

代码提交

summarize the changes I’ve made to the authentication module create a pr enhance the PR description with more context about the security improvements

反推文档

find functions without proper JSDoc comments in the auth module add JSDoc comments to the undocumented functions in auth.js improve the generated documentation with more context and examples

使用图像

可以拖或ctrl+v粘贴到cli里面 Describe the UI elements in this screenshot Here’s a screenshot of the error. What’s causing it? This is our current database schema. How should we modify it for the new feature? What HTML structure would recreate this component?

引用文件

使用at Explain the logic in @src/utils/auth.js 注意引用目录,只会显示文件列表,而不是内容

使用extended thinking,适用复杂问题,或为新功能创建实现计划

使用 Tab 切换思考功能 或 使用think hard提示启用 I need to implement a new authentication system using OAuth2 for our API. Think deeply about the best approach for implementing this in our codebase. 通过后续提示细化思考 > think about potential security vulnerabilities in this approach think hard about edge cases we should handle

恢复之前的对话

继续之前的工作 –continue 继续最近的对话 –resume 显示对话选择器 claude –continue –print “Continue with my task” //适合脚本或自动化

并行运行 Claude Code 会话

Git worktrees 允许您从同一存储库中检出多个分支到单独的目录中。每个 worktree 都有自己的工作目录,文件隔离,同时共享相同的 Git 历史。

Create a new worktree with a new branch

git worktree add ../project-feature-a -b feature-a

Or create a worktree with an existing branch

git worktree add ../project-bugfix bugfix-123

导航到您的 worktree

cd ../project-feature-a

在此隔离环境中运行 Claude Code

claude

列出所有 worktrees

git worktree list

完成后删除 worktree

git worktree remove ../project-feature-a

linter or code reviewer

linter 静态分析工具 检测语法错误、风格问题或潜在缺陷 // package.json { … “scripts”: { … “lint:claude”: “claude -p ‘you are a linter. please look at the changes vs. main and report any issues related to typos. report the filename and line number on one line, and a description of the issue on the second line. do not return any other text.’” } } changes vs. main //当前分支与主分支之间的代码差异 typos//拼写错误

cat log.txt | claude -p ‘parse this log file for errors’

创建快捷的斜杆命令

echo “Analyze the performance of this code and suggest three specific optimizations:” > .claude/commands/optimize.md 使用> /optimize 斜杆命令还可以传参数 echo ‘Find and fix issue #$ARGUMENTS. Follow these steps: 1. Understand the issue described in the ticket 2. Locate the relevant code in our codebase 3. Implement a solution that addresses the root cause 4. Add appropriate tests 5. Prepare a concise PR description’ > .claude/commands/fix-issue.md /fix-issue 123

寻求帮助

can Claude Code create pull requests?

ios端

用于离开笔记本电脑时启动任务

sub-agents

Use the code-reviewer subagent to check my recent changes 最好在 description 域部分加上 “use PROACTIVELY” or “MUST BE USED”

可以定义一些code-reviewer、debugger 不要尝试让一个子代理做所有事情

First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them

Plugin agents

Use the code-reviewer agent from the security-plugin

内置的子代理

Plan subagent

子代理有自己的上下文,并可以从之前的会话中恢复

Use the code-analyzer agent to start reviewing the authentication module

[Agent completes initial analysis and returns agentId: “abc123”] 恢复:

Resume agent abc123 and now analyze the authorization logic as well

[Agent continues with full context from previous conversation]

Agent Skills

Skills 是模块化功能,通过包含说明、脚本和资源的有组织的文件夹来为 Claude 提供特定领域的专业知识

渐进式披露:Claude 按需分阶段加载信息,而不是预先消耗上下文

每个 Skill 包含一个 SKILL.md 文件(skills目录下),可以写上工作流、最佳实践

Claude Code 仅支持自定义 Skills

Skills 也可以来自 Claude Code 插件 要查看所有可用的 Skills:What Skills are available? or List all available Skills

测试 Skill

示例:如果您的描述提到”PDF 文件”: Can you help me extract text from this PDF? 如果 Claude 不使用您的 Skill, 可将描述更具体(最大1024字符) description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. description: Analyze Excel spreadsheets, create pivot tables, and generate charts. Use when working with Excel files, spreadsheets, or analyzing tabular data in .xlsx format. description: Analyze Excel spreadsheets, generate pivot tables, create charts. Use when working with Excel files, spreadsheets, or .xlsx files.

Skill 1 description: Analyze sales data in Excel files and CRM exports. Use for sales reports, pipeline analysis, and revenue tracking.

Skill 2 description: Analyze log files and system metrics data. Use for performance monitoring, debugging, and system diagnostics. description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes. description: Review code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality. description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages.

共享skills

推荐方法:通过 插件 分发 Skills。当然也可以放在git里面

预置的skills

PowerPoint (pptx):创建演示文稿、编辑幻灯片、分析演示文稿内容 Excel (xlsx):创建电子表格、分析数据、生成带图表的报告

最佳实践

设置合适的自由度 高自由度:

Code review process

  1. Analyze the code structure and organization
  2. Check for potential bugs or edge cases
  3. Suggest improvements for readability and maintainability
  4. Verify adherence to project conventions 中等自由度: ```bash

    Generate report

Use this template and customize as needed:

1
2
3
4
def generate_report(data, format="markdown", include_charts=True):
    # Process data
    # Generate output in specified format
    # Optionally include visualizations
1
2
3
4
5
6
7
8
低自由度:
```bash
## Database migration

Run exactly this script:

```bash
python scripts/migrate.py --verify --backup

Do not modify the command or add additional flags. ``` Claude Haiku (fast, economical):需要提供足够的信息 Claude Sonnet (balanced):逻辑清晰就行 Claude Opus (powerful reasoning):别太过度解释

命名用 动名词形式,如processing-pdfs https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices

保持 SKILL.md 正文在 500 行以下

如果引用的文件内容超过100行,可以在最前面放个目录

对复杂任务使用工作流

可以分解为清晰的顺序步骤。对于特别复杂的工作流,提供一个清单

可以让claude协助设计skills提示词,因为 Claude 模型既理解如何编写有效的agent instructions ,也理解agent需要什么信息 Create a Skill that captures this BigQuery analysis pattern we just used. Include the table schemas, naming conventions, and the rule about filtering test accounts. 如果发现有遗漏: When Claude used this Skill, it forgot to filter by date for Q4. Should we add a section about date filtering patterns I noticed Claude B forgot to filter test accounts when I asked for a regional report. The Skill mentions filtering, but maybe it’s not prominent enough?

编写技能脚本时,处理错误条件而不是推卸给 Claude。

本文由作者按照 CC BY 4.0 进行授权