Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Claude Code Basics

Claude Code Basics

This chapter introduces the core features most commonly used in Claude Code daily development, including how to converse with Claude, read and modify code, execute commands, handle files, and some practical tips that can greatly improve efficiency.


Basic conversation methods

1. Interactive mode (most commonly used)

Start Claude Code in the project directory; once in interactive mode, you can directly enter questions or instructions:

cd /path/to/your/project
claude

In interactive mode, just enter natural language; no special format is needed:

这个项目是做什么的?
帮我找出 src/auth.ts 里的 bug
给 UserService 添加一个 getUserById 方法

You can use the @ symbol to specify a file; for example, we have a test.html in the claude-test directory.

We can enter claude-test:

cd claude-test

Then ask:


@test.html 这个文件是干嘛的

2. One-off task mode

If you only need to perform one task and don't need to enter interactive mode, you can append the task description directly to the command:

claude "解释一下 package.json 里的 scripts 字段"

It exits automatically after execution, suitable for use in shell scripts or quick queries.

3. Single-query mode (-p)

Use -p Use the flag to perform a one-off query; Claude's answer is output directly to the terminal, suitable for combining with other commands:

claude -p "这段代码有什么问题" < src/utils.ts
# 将 Claude 的分析结果保存到文件
claude -p "分析项目依赖的安全风险" > security-report.md

4. Continue the previous conversation (-c)

Claude Code saves conversation history. Use the -c flag to continue the most recent unfinished conversation in the current directory, without re-establishing context:

claude -c

Understanding and analyzing code

1. Understand the overall project

When you first enter an unfamiliar project, you can have Claude do an overall analysis:

这个项目的架构是怎样的?
项目用了哪些主要的技术和依赖?
请介绍一下项目的目录结构

Claude Code automatically reads project files for analysis;you don't need to manually specify which files to read— it determines on its own what needs to be looked at.

2. Analyze a specific file or module

解释一下 src/middleware/auth.ts 的工作原理
UserRepository 类里有哪些方法?分别是做什么的?
这个 SQL 查询语句是什么意思?

3. Trace the code call chain

当用户登录时,代码执行流程是怎样的?从入口到数据库全部列出来
findUserByEmail 这个函数在哪里被调用?
这个接口的数据最终存到了哪张数据库表里?

4. Understand complex logic

这段递归函数是什么意思?能举个例子说明吗?
为什么这里要用 useCallback?不用会怎样?
这个正则表达式能匹配什么格式的字符串?

Modify the code

1. Add a new feature

Describe the feature you need, and Claude will find the appropriate place and implement it:

在 UserService 里添加一个 updatePassword 方法,需要验证旧密码
给登录接口添加请求频率限制,同一 IP 每分钟最多 5 次
创建一个 formatCurrency 工具函数,支持传入货币代码参数

2. Fix a bug

Describe the symptoms, and Claude will locate the cause and propose a fix:

用户登出后刷新页面仍然显示已登录状态,帮我找出原因并修复
这个函数在输入为空数组时会报错,修复它
控制台报错 "Cannot read properties of undefined (reading 'map')",帮我定位并修复

3. Refactor code

把这个 500 行的组件拆分成更小的子组件
将 callback 风格的异步代码改为 async/await
这几个函数里有大量重复代码,帮我提取成通用函数

4. Review changes

Claude Code shows a diff before every file modification for your review. You can discuss after Claude proposes a change:

先不要改代码,只告诉我你打算怎么修改
你刚才的修改有个问题:没有处理并发情况,重新来过
这个方案可以,但把函数名改成 validateUserCredentials

Before performing any file modification, Claude Code displays the changes and asks for your confirmation. You can choose toaccept (yes)、reject (no), or continue discussing before confirming. Don't feel you must accept all changes at once — review first, then confirm if it looks good.


Executing commands and tests

1. Have Claude run commands

Claude Code can execute commands directly in the terminal; you can describe what you want in natural language:

运行测试,看看有没有失败的
安装 dayjs 这个依赖
把项目构建一下,看看有没有报错

Claude will choose the correct command to execute based on project configuration (such as package.json scripts in or CLAUDE.md commands in ).

2. Run specific tests

运行 auth 模块的测试
运行所有测试并生成覆盖率报告
这个测试为什么失败了?帮我修复

3. View command output

Claude uses the command output as context and gives next-step suggestions directly based on it:

运行 npm run build,如果有报错帮我修复
跑一下 lint,把所有警告都修复掉

File operations

1. Create a new file

创建 src/utils/date.ts,实现日期格式化相关的工具函数
新建一个 Docker Compose 配置文件,包含 PostgreSQL 和 Redis 服务
创建 .github/workflows/ci.yml,配置 GitHub Actions 自动运行测试

2. Find files and content

项目里有没有处理文件上传的代码?在哪里?
哪些地方用到了 localStorage?
找出所有使用了 console.log 的文件

3. Batch modifications

把所有文件里的 http://api.example.com 替换成 https://api.example.com
把 src/components/ 下所有组件的 PropTypes 改为 TypeScript 类型定义
给 src/api/ 目录下所有接口函数添加 JSDoc 注释

Git operations

Claude Code is deeply integrated with Git and can perform almost all Git operations using natural language.

1. View changes

我改了哪些文件?
这次的改动有哪些内容?
最近 10 次提交都改了什么?

2. Commit code

提交这次的改动
把这次的修改提交,commit 信息说明修复了登录验证的 bug

Claude automatically generates a conventional commit message based on the actual changes; you can also use a shortcut command:

claude commit

3. Branch management

新建一个 feature/user-profile 分支
切换到 develop 分支
把 main 分支的最新改动合并进来

4. Handle merge conflicts

帮我解决合并冲突
这个文件有冲突,帮我看看哪个版本是正确的

Context management tips

1. Manually specify files

Use @文件路径 The syntax lets you clearly tell Claude which file to reference, avoiding guesswork:

参考 @src/types/user.ts 里的类型定义,给 UserService 添加类型注解
对照 @docs/api-spec.md 里的规范,检查接口实现是否符合要求

2. Clear context

When a conversation has run for a long time, or you switch to a completely different task, it's recommended to clear the context and start fresh:

/clear

After clearing, Claude's "memory" returns to its initial state, and the new session is unaffected by previous conversation content.

3. Compress context

When Claude seems to start "forgetting" earlier content, or the conversation becomes very long, you can compress the context:

/compact

This makes Claude summarize the current conversation into a compact summary, freeing up context space while retaining key information to continue working.

4. Split tasks sensibly

Don't describe a complex task all at once; splitting it into several steps works better:

❌ Bad practice: throwing too many requirements at Claude at once:

"帮我重构整个用户模块,包括添加类型注解、拆分文件、
优化数据库查询、添加缓存、写测试、更新文档"

✅ Good practice: splitting into independent steps in logical order:


第一步:"分析 src/user/ 目录的现有结构,告诉我有哪些问题"
第二步:"先给所有函数添加 TypeScript 类型注解"
第三步:"把超过 200 行的文件拆分成更小的模块"
第四步:"优化数据库查询,添加必要的索引"

Common slash commands

In interactive mode, enter / to pop up a list of all available commands. The most commonly used slash commands are:

Command Function Use Cases
/help View all available commands and feature descriptions When you don't know what features are available
/clear Clear conversation history and start a new session When switching to a new task
/compact Compress the current conversation context to free up space When the conversation is long and Claude starts forgetting
/init Analyze the project and generate a CLAUDE.md file When first using it in a new project
/resume Select and restore a previous conversation from history Continue an unfinished task from yesterday
/undo Undo the last file modification When Claude's changes are not right
/redo Redo an undone change After undoing, you find the original was better
/login Log in or switch accounts When you need to switch to another account
/config View and modify configuration Adjust Claude Code behavior settings
/cost View the token usage for this session Monitor costs when using an API account

Practical tips

1. Have Claude analyze first, then act

For complex problems, first have Claude explain its approach, then execute after confirming the direction is right:

不要修改代码,先分析登录失败的可能原因,列出你的排查思路
你打算怎么实现这个功能?先描述方案,我确认后再写代码

2. Provide error messages and logs

When an error occurs, paste the error message directly into the conversation, and Claude will locate the problem based on it:

运行时报了这个错误,帮我分析原因:
TypeError: Cannot read properties of null (reading 'userId')
    at getUserProfile (src/services/user.ts:42:18)
    at async ProfileController.getProfile (src/controllers/profile.ts:15:20)

3. Use screenshots to describe UI issues

Claude Code supports multimodal input; you can paste screenshots directly into the conversation to describe UI-related problems:

[粘贴截图] 这个按钮点击后没有反应,但控制台没有报错,帮我排查
[粘贴设计稿截图] 按照这个设计实现 Header 组件

4. Make good use of "continue"

If Claude's answer is cut off, or you feel it hasn't finished, simply say "continue":

继续
还有吗?
把剩下的部分也实现了

5. Ask for explanations of changes

For important code changes, you can ask Claude to explain the reason for each change:

修改完之后给我解释一下每处改动的目的
这里为什么要用 Promise.allSettled 而不是 Promise.all?

6. Limit Claude's scope of operation

When you don't want Claude to change other files arbitrarily, you can clearly limit the scope:

只修改 src/auth.ts 这一个文件,不要改其他地方
只读取代码不要修改,帮我分析这个模块的性能瓶颈

Common workflow examples

Workflow 1: Quickly understand a new project

Example

Step 1: Start and understand the project

What does this project do? What technologies does it use?

Step 2: Understand the directory structure

Describe the project's directory structure, focusing on the core modules

Step 3: Learn how to run it

How do I run this project locally?

Step 4: Generate a project description file

Help me generate a CLAUDE.md file summarizing the project's key information

Workflow 2: Fix a bug

Example

Step 1: Describe the problem

User report: after modifying personal information, the username at the top of the page does not update in real time

Step 2: Have Claude analyze the cause

First analyze the possible causes; don't modify the code

Step 3: Fix after confirming the plan

The second cause you mentioned seems more likely; fix it along those lines

Step 4: Verify the fix

Run the relevant tests to confirm the fix works

Workflow 3: Add a new feature

Example

Step 1: Describe the requirement

Need to add status filtering to the order list; statuses are: pending payment, paid, shipped, completed

Step 2: Understand the existing code

First look at the existing code structure related to orders

Step 3: Implement the feature

Implement the filtering feature without affecting existing functionality

Step 4: Add tests

Write test cases for this new feature

Step 5: Commit the code

Commit these changes

Workflow 4: Code review


# Review specific file
> 帮我审查 src/payment/processor.ts 这个文件,
> 重点关注错误处理、边界情况和安全风险

# Review git changes
> 审查我这次的所有改动,看看有没有明显的问题

# Targeted check
> 这段代码有没有 SQL 注入的风险?

Notes

Regarding file modifications: Claude Code displays a diff and asks for confirmation before modifying;don't blindly accept everything, especially changes involving core logic; read the diff carefully before deciding whether to accept.

Regarding sensitive files: In CLAUDE.md or .claude/settings.json files explicitly marked as not to be read or modified by Claude in (such as .env, key files), to avoid accidental exposure.

Regarding large tasks: Don't pile up too many unfinished tasks in one conversation; it can cause Claude to lose focus. Finish one task before starting the next, or use /clear to start over.

Regarding code quality: The code Claude generates is not always optimal; for important modules, it's recommended to do a round of code review after execution, understand the purpose of each change, and ensure it conforms to the project's design principles.