Skip to content

日常工作:掌握常见工作流

现在您已经完成了设置,让我们探索 Claude Code 如何成为您日常工作中不可或缺的一部分。本章侧重于您将反复遇到的实用、真实世界的应用程序。我们的目标是让使用 Claude Code 感觉就像使用您的代码编辑器或版本控制一样自然。

启动新组件、Web 服务器或实用脚本通常涉及编写重复的样板代码 (boilerplate)。让我们把这项工作卸载掉。例如,要创建一个简单的 Flask Web 服务器,您可以给出一条命令:

> Create an app.py file with a simple Flask application. It should have a single route '/' that returns 'Hello from Claude Code!'.

Claude Code 将生成包含所有必要导入和代码的文件。这使您免于繁琐的设置,让您可以直接着手构建应用程序的独特功能。

编写全面的单元测试 (unit tests) 对于健壮的软件至关重要,但这可能很单调。Claude Code 在这方面表现出色。想象一下,您在名为 utils.py 的文件中有一个 Python 函数,内容如下:

utils.py
def format_user_greeting(name, is_premium):
if not name:
return "Hello, guest!"
greeting = f"Hello, {name}!"
if is_premium:
greeting += " Welcome to our premium service."
return greeting

您可以要求 Claude Code 使用 pytest 等框架为其生成测试:

> In a new file `test_utils.py`, write pytest unit tests for the `format_user_greeting` function in `utils.py`. Cover the guest user, standard user, and premium user cases.

Claude Code 将读取 utils.py,理解函数逻辑,并生成一个新的 test_utils.py 文件,其中包含您指定的确切用例的全面测试,包括必要的导入和断言。

我们都遇到过难以阅读和维护的函数。Claude Code 可以成为改进它们的客观伙伴。假设您有一个复杂的函数。您可以简单地请求帮助:

> @my_complex_file.js Refactor the `processData` function on line 52 to use modern JavaScript syntax like async/await and make it more readable by breaking it into smaller helper functions.

通过引用特定文件 (@my_complex_file.js) 和函数,您提供了必要的上下文。Claude Code 将提出一个重构版本,该版本在保留原始逻辑的同时提高了代码质量。这对于现代化遗留代码库 (legacy codebases) 或仅仅清理您自己的工作来说是无价的。

盯着堆栈跟踪 (stack trace) 可能是开发中最令人沮丧的部分之一。让 Claude Code 看一看。只需复制整个错误消息和堆栈跟踪并将其粘贴到 prompt (提示) 中:

> I'm getting this error when running my script. Can you explain what's wrong and suggest a fix?
Traceback (most recent call last):
File "/app/data_processor.py", line 78, in <module>
process_records(user_data)
File "/app/data_processor.py", line 45, in process_records
user['last_login_days_ago'] = (datetime.now() - user['last_login']).days
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'

Claude Code 将立即识别 TypeError,并解释您正在尝试从 datetime 对象中减去一个字符串。然后,它将建议修复方法:在减法之前将 user['last_login'] 字符串转换为 datetime 对象。此工作流将调试从一场追逐变成了简单的对话。

当加入一个新项目或处理一个不熟悉的模块时,首要挑战是了解情况。Claude Code 可以成为您的私人导游。导航到项目根目录并请求概述:

> Give me a high-level overview of this project. What's the main purpose, and what are the key directories or files I should look at first?

它将分析项目结构并提供摘要。然后,您可以提出更具体的问题进行深入探讨:

  • 解释 src/auth/ 中的认证逻辑。

  • 数据如何从 API 控制器流向数据库模型?

  • @src/components/UserProfile.jsx 这个 React 组件的用途是什么?

通过整合这些工作流,您会发现 Claude Code 不仅仅改变了您编写代码的方式,它还改变了您思考和与整个开发过程互动的方式。