风格与规范
Linter、Formatter、团队约定。
25 分钟
风格与规范
「用 tab 还是 space」不该在 PR 里争论。Linter 查问题、Formatter 统一排版,让 Review 聚焦逻辑。团队规范写进配置文件,CI 强制执行,比口头约定可靠。
学习目标
- 区分 Linter 与 Formatter 的职责
- 了解 Java(Checkstyle/Spotless)、JS/TS(ESLint/Prettier)在本站的典型用法
- 将规范与 git-essentials 的 pre-commit 习惯结合
Linter vs Formatter
| Linter | Formatter | |
|---|---|---|
| 目的 | 发现潜在错误、坏模式 | 统一空格、换行、引号 |
| 例子 | 未使用变量、eqeqeq | Prettier、Google Java Format |
| 可否自动修 | 部分 rule 可 --fix | 通常全自动 |
先 format 再 lint,避免 diff 噪音。禁止 --no-verify 跳过 hook,尤其 AI 大批量改文件时,见 ai-coding-essentials。
团队约定写什么
- 命名:包名、REST 路径、React 组件 PascalCase
- 目录结构:backend 分层、platform
src/app路由 - 禁止项:
System.out.println、吞异常、any滥用 - 例外流程:必须
@SuppressWarnings时 PR 说明原因
Spring 项目可对齐 Google Java Style 或团队 fork;与 spring-boot-essentials 包结构一致即可 onboarding。
CI 中的风格门禁
开发者本地:format + lint + test
↓
PR:GitHub Actions 跑 mvn verify / npm run lint
↓
不绿不 merge
platform 侧 ESLint;backend 可在 pom.xml 绑 Checkstyle。下一课 cq-tools 会展开 SonarQube、SpotBugs 等 静态分析。
EditorConfig(.editorconfig)跨 IDE 统一缩进,与 testing-essentials 同属「低成本纪律」。
练习
- 在 platform 跑
npm run lint,修一条 auto-fixable 警告 - 查看 backend 或 platform 的 lint/format 配置文件,列出 2 条 enforced 规则
- 约定:你的下一个 PR 在 push 前本地 lint 绿