一个配置得当的编辑器可以使代码更清晰易读,编写速度更快。它甚至可以帮助你在编写代码时发现错误!如果这是你第一次设置编辑器,或者你想优化当前的编辑器,我们有一些推荐。
🌐 A properly configured editor can make code clearer to read and faster to write. It can even help you catch bugs as you write them! If this is your first time setting up an editor or you’re looking to tune up your current editor, we have a few recommendations.
你将学习到
- 最受欢迎的编辑器是什么
- 如何自动格式化代码
你的编辑器
🌐 Your editor
VS Code 是当今使用最广泛的编辑器之一。它有一个庞大的扩展市场,并且能很好地与 GitHub 等流行服务集成。下面列出的多数功能也可以作为扩展添加到 VS Code,使其高度可配置!
React 社区中使用的其他流行的文本编辑器包括:
🌐 Other popular text editors used in the React community include:
- WebStorm 是专为 JavaScript 设计的集成开发环境。
- Sublime Text 支持 JSX 和 TypeScript,内置了 语法高亮 和自动补齐。
- Vim 是一个高度可配置的文本编辑器,旨在使创建和修改任何类型的文本非常高效。它作为 “vi” 包含在大多数 UNIX 系统以及 Apple OS X 中。
推荐的文本编辑器功能
🌐 Recommended text editor features
一些编辑器内置了这些功能,但其他编辑器可能需要添加扩展。请查看你选择的编辑器提供了哪些支持,以确定!
🌐 Some editors come with these features built in, but others might require adding an extension. Check to see what support your editor of choice provides to be sure!
代码检查
🌐 Linting
代码检查工具在你编码时会发现问题,帮助你及早修复。ESLint 是一个流行的开源 JavaScript 检查工具。
🌐 Code linters find problems in your code as you write, helping you fix them early. ESLint is a popular, open source linter for JavaScript.
确保已为你的项目启用所有 eslint-plugin-react-hooks 规则。 它们至关重要,可以及早发现最严重的错误。建议的 eslint-config-react-app 预设已包含这些规则。
格式化
🌐 Formatting
当你与其他贡献者共享代码时,最不想做的事情就是就 制表符与空格 进行讨论!幸运的是,Prettier 会通过重新格式化代码来清理它,使其符合预设的、可配置的规则。运行 Prettier,你的所有制表符都会被转换为空格——同时你的缩进、引号等也都会调整以符合配置。在理想的设置下,每次保存文件时 Prettier 都会运行,为你快速进行这些修改。
🌐 The last thing you want to do when sharing your code with another contributor is get into a discussion about tabs vs spaces! Fortunately, Prettier will clean up your code by reformatting it to conform to preset, configurable rules. Run Prettier, and all your tabs will be converted to spaces—and your indentation, quotes, etc will also all be changed to conform to the configuration. In the ideal setup, Prettier will run when you save your file, quickly making these edits for you.
你可以通过以下步骤在 VSCode 中安装 Prettier 扩展 :
🌐 You can install the Prettier extension in VSCode by following these steps:
- 启动 VS Code
- 使用快速打开(按 Ctrl/Cmd+P)
- 粘贴到
ext install esbenp.prettier-vscode - 按回车
保存时格式化
🌐 Formatting on save
理想情况下,你应该在每次保存时格式化你的代码。VS Code 有此设置!
🌐 Ideally, you should format your code on every save. VS Code has settings for this!
- 在 VS Code 中,按
CTRL/CMD + SHIFT + P。 - 输入“设置”
- 回车
- 在搜索栏中,输入“保存时格式化”
- 确保勾选了“保存时格式化”选项!
如果你的 ESLint 预设包含格式化规则,它们可能会与 Prettier 冲突。我们建议使用
eslint-config-prettier禁用 ESLint 预设中的所有格式化规则,以便 ESLint 仅 用于捕捉逻辑错误。如果你希望在合并拉取请求之前强制文件格式化,请在持续集成中使用prettier --check。