awesome-code-standards
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCoding Standards
编码标准
Apply consistent naming, structure, and patterns so code is readable and maintainable across the team.
采用统一的命名、结构和模式,确保团队内代码的可读性和可维护性。
When to Activate
适用场景
- Starting a new project or module
- Refactoring to match team conventions
- Setting up or updating lint/format/type-check rules
- Reviewing code for consistency
- Onboarding: documenting or applying coding conventions
- Enforcing naming, formatting, or structural consistency
- 启动新项目或新模块
- 按照团队规范进行重构
- 配置或更新lint/格式化/类型检查规则
- 审查代码一致性
- 新人入职:编写编码规范文档或落地规范
- 推行命名、格式或结构一致性
Core Principles
核心原则
- Readability first — Code is read more than written; clear names and structure beat clever tricks.
- KISS — Simplest solution that works; avoid over-engineering and premature optimization.
- DRY — Extract common logic into functions/modules; avoid copy-paste.
- YAGNI — Don't build for speculative future needs; add complexity when required.
- Immutability — Prefer const; avoid mutating arguments or shared state; use spread/copy where needed.
- 可读性优先 — 代码的阅读次数远多于编写次数;清晰的命名和结构胜过巧妙的技巧。
- KISS原则 — 采用能解决问题的最简单方案;避免过度设计和过早优化。
- DRY原则 — 将通用逻辑抽取到函数/模块中;避免复制粘贴。
- YAGNI原则 — 不要为推测的未来需求做构建;只在需要时增加复杂度。
- 不可变性 — 优先使用const;避免修改参数或共享状态;必要时使用展开运算符/拷贝操作。
Work Process (when applying standards)
(应用规范时的)工作流程
- Discover project conventions — Scan existing code: naming (camelCase vs snake_case), file layout, import style, test patterns. Check for CONTRIBUTING, .eslintrc, .prettierrc, or editorconfig.
- Identify violations — Compare changed or new code against those conventions and the rules below.
- Suggest concrete fixes — Rename symbols, extract functions, add types, fix formatting. Prefer one logical edit per suggestion.
- Document exceptions — If the project has an exception (e.g. "use any here for legacy"), note it rather than "fixing" it without context.
- 了解项目现有约定 — 浏览现有代码:命名风格(camelCase还是snake_case)、文件布局、导入风格、测试模式。检查是否有CONTRIBUTING、.eslintrc、.prettierrc或editorconfig文件。
- 识别违规点 — 将变更或新增代码与上述约定及以下规则进行对比。
- 给出具体修复建议 — 重命名符号、抽取函数、添加类型、修正格式。每条建议最好只包含一个逻辑修改。
- 记录例外情况 — 如果项目有特殊约定(例如“此处因历史遗留问题使用any”),请记录下来,不要脱离上下文强行“修复”。
Naming Conventions
命名规范
Variables and functions
变量与函数
typescript
// GOOD: Descriptive, verb-noun for functions
const marketSearchQuery = 'election';
const isUserAuthenticated = true;
async function fetchMarketData(marketId: string) {}
function calculateSimilarity(a: number[], b: number[]) {}
// BAD: Unclear or noun-only for actions
const q = 'election';
const flag = true;
async function market(id: string) {}
function similarity(a, b) {}typescript
// GOOD: Descriptive, verb-noun for functions
const marketSearchQuery = 'election';
const isUserAuthenticated = true;
async function fetchMarketData(marketId: string) {}
function calculateSimilarity(a: number[], b: number[]) {}
// BAD: Unclear or noun-only for actions
const q = 'election';
const flag = true;
async function market(id: string) {}
function similarity(a, b) {}Constants
常量
- UPPER_SNAKE for true constants (e.g. ,
MAX_RETRIES).API_BASE_URL - Or project convention (some codebases use camelCase for config objects).
- 真正的常量使用大写下划线命名(例如 、
MAX_RETRIES)。API_BASE_URL - 或遵循项目约定(部分代码库对配置对象使用camelCase)。
Types and interfaces
类型与接口
- PascalCase: ,
User,OrderItem.ApiResponse<T> - Suffix with role if helpful: ,
CreateUserRequest.UserResponse
- 使用PascalCase:、
User、OrderItem。ApiResponse<T> - 必要时添加角色后缀:、
CreateUserRequest。UserResponse
Files
文件命名
- Components: PascalCase (,
Button.tsx).UserProfile.tsx - Utilities/hooks: camelCase (,
formatDate.ts).useAuth.ts - Types: camelCase with or
.typesas project uses (.d).market.types.ts
- 组件:使用PascalCase(、
Button.tsx)。UserProfile.tsx - 工具函数/hooks:使用camelCase(、
formatDate.ts)。useAuth.ts - 类型文件:使用camelCase,按项目习惯加或
.types后缀(.d)。market.types.ts
Other languages
其他语言
The examples above are TypeScript; the rule is "follow the language's own published convention", and that convention differs. Each language's style guide wins over the casing shown here:
- Python (PEP 8) — functions, variables, modules;
snake_caseclasses;PascalCaseconstants; a leadingUPPER_SNAKEmarks non-public._ - Go (Effective Go) — , never underscores; a capital initial is the export marker. The package name is part of the name:
MixedCaps, notchi.NewRouter.chi.NewChiRouter - Rust (RFC 430) — functions, variables, modules;
snake_casetypes and traits;UpperCamelCaseconsts and statics.SCREAMING_SNAKE_CASE - Java / Kotlin — methods and fields,
camelCasetypes, one public type per file named after it.PascalCase - C# — for methods, properties, and types;
PascalCasefor locals and parameters; interfaces prefixedcamelCase.I
以上示例基于TypeScript;核心规则是“遵循语言本身的官方约定”,不同语言的约定存在差异。各语言的风格指南优先级高于此处列出的大小写规则:
- Python(PEP 8)— 函数、变量、模块使用;类使用
snake_case;常量使用PascalCase;前缀UPPER_SNAKE表示非公开。_ - Go(Effective Go)— 使用,绝不使用下划线;首字母大写就是导出标记。包名是名称的一部分:应使用
MixedCaps,而非chi.NewRouter。chi.NewChiRouter - Rust(RFC 430)— 函数、变量、模块使用;类型和trait使用
snake_case;常量和静态变量使用UpperCamelCase。SCREAMING_SNAKE_CASE - Java / Kotlin — 方法和字段使用,类型使用
camelCase,每个文件仅包含一个与文件名同名的公共类型。PascalCase - C# — 方法、属性和类型使用;局部变量和参数使用
PascalCase;接口加camelCase前缀。I
Immutability (critical)
不可变性(关键)
typescript
// GOOD: Spread and new references
const updatedUser = { ...user, name: 'New Name' };
const updatedArray = [...items, newItem];
// BAD: Direct mutation
user.name = 'New Name';
items.push(newItem);Other languages — same rule, different mechanism:
- Python — never mutate an argument the caller still owns, and never use a mutable default (shares one list across calls; use
def f(xs=[])+ build inside). Prefer tuples andNonefor fixed collections;frozensetfor a modified copy.dataclasses.replace(obj, field=…) - Go — a slice you store keeps its caller's backing array, so can write through to it later; copy before retaining (
append). Value receivers for methods that shouldn't mutate.slices.Clone - Rust — bindings are immutable by default and the borrow checker enforces it; is the exception you justify, not the default you type.
mut - Java — for data carriers,
record/List.copyOffor defensive copies at the boundary.Map.copyOf - C# — types plus
recordexpressions;with/ImmutableArrayfor shared collections.ImmutableList
typescript
// GOOD: Spread and new references
const updatedUser = { ...user, name: 'New Name' };
const updatedArray = [...items, newItem];
// BAD: Direct mutation
user.name = 'New Name';
items.push(newItem);其他语言 — 规则相同,实现方式不同:
- Python — 永远不要修改调用方仍持有的参数,永远不要使用可变默认值(会在多次调用间共享同一个列表;应使用
def f(xs=[])并在函数内部构建)。固定集合优先使用元组和None;使用frozenset生成修改后的副本。dataclasses.replace(obj, field=…) - Go — 你存储的slice会保留调用方的底层数组,因此后续的操作可能会修改原数组;在保留slice前先拷贝(使用
append)。不需要修改接收者的方法应使用值接收者。slices.Clone - Rust — 绑定默认是不可变的,由借用检查器强制保证;是需要理由的例外,而非默认写法。
mut - Java — 数据载体使用,在边界处使用
record/List.copyOf做防御性拷贝。Map.copyOf - C# — 使用类型搭配
record表达式;共享集合使用with/ImmutableArray。ImmutableList
Error Handling
错误处理
typescript
// GOOD: Validate, throw or return with context
async function fetchData(url: string) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Fetch failed:', error);
throw new Error('Failed to fetch data');
}
}
// BAD: No handling or swallowed errors
async function fetchData(url: string) {
const response = await fetch(url);
return response.json();
}Other languages — the shape changes, "add context, never swallow" does not:
- Python — raise a specific exception type, never a bare (it eats
except:too). Re-raise with the chain intact:KeyboardInterrupt.raise ParseError(...) from err - Go — errors are values: check every one, wrap with context using so
%w/errors.Isstill work (errors.As). Discarding one withfmt.Errorf("fetch %s: %w", url, err)needs a comment saying why it's safe._ = - Rust — return and propagate with
Result<T, E>; a typed error enum (or?) at library boundaries,thiserroronly in the binary.anyhow/unwrap()in library code is a panic you shipped.expect() - Java — one exception type per failure mode, never an empty ; keep the cause (
catch).throw new X(msg, err) - C# — catch the specific exception, rethrow with bare (not
throw;, which resets the stack trace).throw ex;
typescript
// GOOD: Validate, throw or return with context
async function fetchData(url: string) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Fetch failed:', error);
throw new Error('Failed to fetch data');
}
}
// BAD: No handling or swallowed errors
async function fetchData(url: string) {
const response = await fetch(url);
return response.json();
}其他语言 — 形式不同,但“添加上下文,绝不吞错误”的原则不变:
- Python — 抛出具体的异常类型,绝不使用裸(它会捕获
except:)。重新抛出时保留异常链:KeyboardInterrupt。raise ParseError(...) from err - Go — 错误是值:每个错误都要检查,使用包装上下文以保证
%w/errors.Is仍可使用(errors.As)。若用fmt.Errorf("fetch %s: %w", url, err)忽略错误,必须添加注释说明为何安全。_ = - Rust — 返回,使用
Result<T, E>传播错误;库边界处使用带类型的错误枚举(或?),仅在二进制程序中使用thiserror。库代码中的anyhow/unwrap()相当于你把panic发布给了用户。expect() - Java — 每种失败模式对应一个异常类型,绝不使用空;保留异常原因(
catch)。throw new X(msg, err) - C# — 捕获具体异常,使用裸重新抛出(不要用
throw;,那会重置栈追踪)。throw ex;
Async and concurrency
异步与并发
typescript
// GOOD: Parallel when independent
const [users, markets, stats] = await Promise.all([
fetchUsers(),
fetchMarkets(),
fetchStats(),
]);
// BAD: Sequential when unnecessary
const users = await fetchUsers();
const markets = await fetchMarkets();
const stats = await fetchStats();Other languages — run independent work concurrently, and give every concurrent unit a way to be cancelled:
- Python — for independent awaits;
asyncio.gather(*coros)(3.11+) when a failure should cancel the siblings. Blocking calls go toasyncio.TaskGroup, never inline in a coroutine.run_in_executor - Go — (
errgroup.Group) for fan-out that must fail as a unit,golang.org/x/syncwhen it must not.sync.WaitGroupis the first parameter of anything that can block, and it is passed down, not stored in a struct.context.Context - Rust — for independent futures,
tokio::join!when the first error should abort; atry_join!or dropping theCancellationTokenfor teardown.JoinHandle - Java — , or structured concurrency (
CompletableFuture.allOf(...)) where available.StructuredTaskScope - C# — , with a
Task.WhenAll(...)threaded through every async signature.CancellationToken
typescript
// GOOD: Parallel when independent
const [users, markets, stats] = await Promise.all([
fetchUsers(),
fetchMarkets(),
fetchStats(),
]);
// BAD: Sequential when unnecessary
const users = await fetchUsers();
const markets = await fetchMarkets();
const stats = await fetchStats();其他语言 — 独立任务并发执行,且每个并发单元都要有取消机制:
- Python — 独立的await操作使用;若某个任务失败需取消其他兄弟任务,使用
asyncio.gather(*coros)(3.11+)。阻塞调用应放到asyncio.TaskGroup中,绝不能直接写在协程里。run_in_executor - Go — 需要整体失败的扇出场景使用(
errgroup.Group),不需要整体失败的使用golang.org/x/sync。所有可能阻塞的操作,sync.WaitGroup都是第一个参数,且必须向下传递,不能存在结构体里。context.Context - Rust — 独立的future使用,遇到第一个错误就中止的场景使用
tokio::join!;销毁时使用try_join!或直接丢弃CancellationToken。JoinHandle - Java — 使用,或在支持的环境下使用结构化并发(
CompletableFuture.allOf(...))。StructuredTaskScope - C# — 使用,每个异步方法签名都要传递
Task.WhenAll(...)。CancellationToken
Type Safety
类型安全
typescript
// GOOD: Explicit types, no any
interface Market {
id: string;
name: string;
status: 'active' | 'resolved' | 'closed';
}
function getMarket(id: string): Promise<Market> { /* ... */ }
// BAD: any or untyped
function getMarket(id: any): Promise<any> { /* ... */ }Other languages — the goal is the same: make an invalid value unrepresentable, and check it at the boundary rather than at every call site.
- Python — annotate every public signature and run /
mypyin strict mode in CI; a type hint nothing checks is a comment.pyright/TypedDict/Pydantic model at API and parse boundaries, not rawdataclass.dict[str, Any] - Go — concrete types over ; accept interfaces, return structs. An
anyin a signature is a parse boundary, and it gets a type switch oranyimmediately.errors.As - Rust — newtypes over bare primitives (, not
struct UserId(u64)) so the compiler catches a swapped argument; enums over stringly-typed state.u64 - Java / Kotlin — Kotlin's nullable types, or plus nullability annotations in Java; no
Optionalin a public signature.Object - C# — nullable reference types enabled project-wide (), warnings as errors.
<Nullable>enable</Nullable>
Dynamically-typed languages without a checker (plain JS, Ruby, PHP, Lua) do the same job at runtime: validate at the trust boundary with a schema, and let internal calls stay unguarded.
typescript
// GOOD: Explicit types, no any
interface Market {
id: string;
name: string;
status: 'active' | 'resolved' | 'closed';
}
function getMarket(id: string): Promise<Market> { /* ... */ }
// BAD: any or untyped
function getMarket(id: any): Promise<any> { /* ... */ }其他语言 — 目标一致:让非法值无法被表示,在边界处做检查,而非在每个调用点都检查。
- Python — 所有公共签名都要加类型注解,CI中以严格模式运行/
mypy;没有检查机制的类型注解只是注释。API和解析边界处使用pyright/TypedDict/Pydantic模型,而非原始的dataclass。dict[str, Any] - Go — 优先使用具体类型而非;接收接口,返回结构体。签名中的
any意味着这是解析边界,必须立即做类型断言或any处理。errors.As - Rust — 使用newtype包装原生基本类型(用而非
struct UserId(u64)),让编译器捕获参数传反的问题;状态使用枚举而非字符串类型。u64 - Java / Kotlin — Kotlin使用可空类型,Java使用加可空性注解;公共签名中不要出现
Optional。Object - C# — 全项目启用可空引用类型(),警告视为错误。
<Nullable>enable</Nullable>
没有类型检查器的动态类型语言(原生JS、Ruby、PHP、Lua)在运行时实现相同目标:在信任边界处用schema做校验,内部调用无需额外防护。
Comments and docs
注释与文档
- Explain why, not what — "Use exponential backoff to avoid overwhelming the API" not "Increment retry count." A comment that only restates the code is noise; delete it or rename the code so it isn't needed.
- Plain ASCII punctuation — Write comments the way a developer types them: not
-,—not..., straight quotes, no decorative glyphs or emoji. Typographic glyphs in a comment are an AI-generation tell, not house style. (Comment text only — never string literals, identifiers, or data.)… - Doc comments on public APIs — Summary, parameters, return, what it raises, optional example. Use the language's own format and match project style: JSDoc/TSDoc, Python docstrings (PEP 257, in the project's Google/NumPy/reST flavor), Go doc comments starting with the symbol name, Rust with a
///section, Javadoc, XML doc comments in C#.# Examples - No commented-out code — Remove or explain in a ticket; use version control for history.
That is the bar for code you are writing or touching now. For a repo-wide pass over existing comments — deciding what to delete, condense, or fix, with the false-positive boundaries and the behavior-preserving verification gate — use awesome-code-cleanup, which owns that procedure.
- 解释为什么,而非做什么 — 应该写“使用指数退避避免压垮API”,而非“增加重试计数”。仅仅复述代码的注释是噪音;要么删掉,要么重命名代码让注释变得多余。
- 使用纯ASCII标点 — 按开发者日常输入的方式写注释:用而非
-,用—而非...,用直引号,不要装饰性符号或emoji。注释中的排版符号是AI生成的特征,而非团队风格。(仅针对注释文本——字符串字面量、标识符、数据不受此限。)… - 公共API必须有文档注释 — 包含摘要、参数、返回值、抛出异常说明,可选示例。使用对应语言的原生格式并匹配项目风格:JSDoc/TSDoc、Python docstring(PEP 257,遵循项目采用的Google/NumPy/reST风格)、Go的文档注释以符号名开头、Rust的注释包含
///章节、Javadoc、C#的XML文档注释。# Examples - 不要保留注释掉的代码 — 要么删掉,要么在工单中说明原因;历史代码用版本控制管理。
以上是你当前编写或修改代码时应遵循的标准。如果需要对全仓库现有注释做批量处理——判断哪些该删、该精简、该修复,同时明确误判边界和行为不变性验证门槛——请使用awesome-code-cleanup,该场景由它负责。
File and project structure
文件与项目结构
- Follow existing layout (e.g. ,
src/app/,src/components/).src/lib/ - One main export per file unless the project uses barrel files or index re-exports.
- Group imports: stdlib → third-party → local; alphabetical or by path per project.
- 遵循现有布局(例如 、
src/app/、src/components/)。src/lib/ - 每个文件仅包含一个主要导出,除非项目使用桶文件(barrel file)或index重导出。
- 导入分组:标准库 → 第三方库 → 本地模块;按项目习惯排序(字母序或路径序)。
Backend layering and boundaries (when applicable)
后端分层与边界(如适用)
- Three-model split — keep DTO/API models, domain models, and persistence/ORM models separate. One object flowing through transport, business logic, and storage traps API shape to table shape and makes every refactor touch every layer.
User - Layer-placement heuristic — needs HTTP status codes → edge/controller; needs business rules → service; needs tables/indexes/ORM → repository. Flow one direction: .
controller -> service -> repository -> gateway - Cross-cutting concerns once at the edge — auth, validation, rate-limit, request IDs, logging live in the HTTP pipeline (global middleware/hooks or route-scoped setup), never hand-copied into each handler. The rule: do not repeat policy by hand in every endpoint.
- Errors don't know transport — services and repositories throw domain errors; one global handler maps them to status codes.
- Contract-first — OpenAPI (or equivalent) is the single source of truth for request/response shapes; generate typed clients from it and fail CI on spec drift.
typescript
// GOOD: service throws a domain error; the global handler maps NotFoundError -> 404
throw new NotFoundError('market', id);
// BAD: business logic reaches into HTTP transport
return res.status(404).json({ error: 'not found' });This section only places the layers. Designing the error envelope, HTTP status mapping, and retry policy in depth is awesome-error-standards' job — go there when the task is the error contract itself.
- 三模型分离 — 将DTO/API模型、领域模型、持久化/ORM模型分开。如果同一个对象贯穿传输层、业务逻辑和存储层,会导致API结构与表结构绑定,每次重构都要修改所有层。
User - 分层放置准则 — 需要HTTP状态码 → 边缘层/控制器;需要业务规则 → 服务层;需要表/索引/ORM → 仓储层。调用方向单向流动:。
controller -> service -> repository -> gateway - 横切关注点统一在边缘层处理 — 鉴权、校验、限流、请求ID、日志都放在HTTP管道中(全局中间件/hooks或路由级配置),绝不要手动复制到每个handler里。规则:不要在每个端点中手写重复的策略。
- 错误不感知传输层 — 服务层和仓储层抛出领域错误;由全局处理器统一映射为状态码。
- 契约优先 — OpenAPI(或等价规范)是请求/响应结构的唯一事实来源;基于它生成带类型的客户端,规范不一致时CI直接失败。
typescript
// GOOD: service throws a domain error; the global handler maps NotFoundError -> 404
throw new NotFoundError('market', id);
// BAD: business logic reaches into HTTP transport
return res.status(404).json({ error: 'not found' });本节仅涉及分层定位。深入设计错误信封、HTTP状态映射和重试策略是awesome-error-standards的职责——如果任务是错误契约本身,请使用该技能。
Code smells to fix
需要修复的代码坏味道
| Smell | Action |
|---|---|
| Function > ~50 lines | Split into smaller functions with clear names |
| Deep nesting (5+ levels) | Use early returns or extract functions |
| Magic numbers | Extract named constants (e.g. |
| Long parameter list | Use options object or split into smaller types |
| Duplicate logic in two places | Extract to shared function or module |
The smells above hold in any language. Numeric thresholds are a starting point, not a law; a documented repo standard always wins, and don't re-flag what a linter or type-checker already enforces. Before inventing a pattern, search the codebase — the problem is often already solved somewhere; reuse it rather than adding a second way to do the same thing.
| 坏味道 | 修复方式 |
|---|---|
| 函数超过约50行 | 拆分为多个命名清晰的小函数 |
| 深层嵌套(5层以上) | 使用提前返回或抽取函数 |
| 魔法数字 | 抽取为具名常量(例如 |
| 参数列表过长 | 使用options对象或拆分为更小的类型 |
| 两处存在重复逻辑 | 抽取到共享函数或模块中 |
以上坏味道适用于所有语言。数值阈值只是起点,并非铁律;有文档记录的仓库标准永远优先级更高,且不要重复标记linter或类型检查器已经强制约束的问题。在发明新模式之前,先搜索代码库——问题通常已经在某处被解决了;复用现有方案,而非新增另一种实现方式。
Framework-specific correctness (when applicable)
框架特定正确性(如适用)
Separate from the universal smells above: every framework has a short list of footguns that look correct and fail at runtime. Learn the list for the framework in front of you rather than assuming another framework's list transfers — the authority is that framework's own documentation (React's Rules of Hooks and "You Might Not Need an Effect", Vue's reactivity caveats, Angular's change-detection guide, Svelte's store and reactivity notes).
React, as the worked example:
| Smell | Action |
|---|---|
| Renders literal |
| Component defined inside another component | Hoist it out — a nested definition is a new type each render and remounts, losing state |
State derivable from props/state kept in | Derive it during render (or use a keyed reset) — no effect needed |
The transferable part is the shape of the class, not these three rows: a falsy value rendering as visible output, an identity that changes every render and silently discards state, and state duplicated instead of derived. Look for that shape in whatever framework the project uses.
与上述通用坏味道不同:每个框架都有一小部分看起来正确但会在运行时出错的坑。请了解当前所用框架的坑,不要想当然地套用其他框架的规则——权威来源是框架本身的文档(React的Hook规则和“你可能不需要Effect”、Vue的响应式注意事项、Angular的变更检测指南、Svelte的store和响应式说明)。
以React为例:
| 坏味道 | 修复方式 |
|---|---|
JSX中写 | 当值为假时会渲染出字面量 |
| 在组件内部定义另一个组件 | 将其提升到外部——嵌套定义会导致每次渲染都生成新类型,触发重挂载,丢失状态 |
可从props/state派生的状态被放在 | 在渲染时直接派生(或使用带key的重置)——不需要effect |
可迁移的是这类问题的模式,而非这三行具体内容:假值被渲染为可见输出、每次渲染标识都变化导致状态静默丢失、状态被重复存储而非派生。无论项目用什么框架,都要留意这类模式。
Frontend rendering and motion (when applicable)
前端渲染与动效(如适用)
- Animate only compositor properties — and
transform. Never animate layout properties (opacity,width,height,top) — they trigger reflow every frame; use the FLIP technique for position changes.margin - Never interleave layout reads and writes in one frame — batch reads (,
getBoundingClientRect) before writes to avoid layout thrashing.offsetWidth - Prefer over JS scroll-event listeners for scroll-linked animation; use
animation-timeline: view()/scroll()surgically and remove it after.will-change - Sensible defaults: on headings,
text-balanceon body,text-prettyfor numeric columns,tabular-numsoverh-dvh, interactions under ~200ms, one accent color per view, a fixed z-index scale.h-screen
- 仅对合成属性做动画 — 和
transform。绝不要对布局属性做动画(opacity、width、height、top)——它们每帧都会触发重排;位置变化使用FLIP技术。margin - 绝不要在一帧中交替进行布局读写 — 把读操作(、
getBoundingClientRect)批量放在写操作之前,避免布局抖动。offsetWidth - 滚动关联动画优先使用,而非JS滚动事件监听器;谨慎使用
animation-timeline: view()/scroll(),用完即移除。will-change - 合理默认值:标题用,正文用
text-balance,数字列用text-pretty,用tabular-nums代替h-dvh,交互响应时间控制在200ms以内,每个视图一个强调色,使用固定的z-index层级。h-screen
Frontend architecture (when applicable)
前端架构(如适用)
- Feature-first folders — product code (pages, feature components, state, feature-scoped API adapters, tests) lives together in a feature/module folder. Shared folders hold only cross-app primitives: design system, app shell, routing bootstrap, global config, i18n. Anti-patterns: a /
shared/commonbucket with no boundary; a giant globalutils; a folder per one-file throwaway.components/ - Colocate — a component or hook that matters keeps its test, story, styles, and an re-export next to it.
index.ts - Route-level code-splitting is the default perf win — lazy-load route chunks; keep dashboard-sized deps out of the initial bundle when the landing page doesn't need them. Profile before hand-optimizing components. (Distinct from the compositor/animation rules above — this is bundle shape, not frame budget.)
- Consume the API contract, don't re-type it — generate TypeScript types from the same OpenAPI spec the backend owns instead of hand-duplicating request/response shapes. Use a server-state library (e.g. TanStack Query) so loading/error/retry stay uniform. Map errors once (a single ) and surface the server
parseApiErrorin error UI so user reports line up with server logs.request_id
- 按功能组织文件夹 — 产品代码(页面、功能组件、状态、功能范围内的API适配器、测试)都放在同一个功能/模块文件夹下。共享文件夹仅存放跨应用的基础内容:设计系统、应用外壳、路由启动配置、全局配置、国际化。反模式:没有明确边界的/
shared/common大杂烩;巨大的全局utils目录;每个一次性单文件都建一个文件夹。components/ - 就近放置 — 重要的组件或hook,其测试、story、样式和重导出文件都放在旁边。
index.ts - 路由级代码分割是默认的性能优化手段 — 懒加载路由块;如果落地页不需要,就不要把仪表盘级别的依赖放进初始包。手动优化组件前先做性能分析。(与上述合成/动画规则不同——这里指的是包结构,而非帧预算。)
- 直接使用API契约,不要重复定义类型 — 基于后端维护的同一份OpenAPI规范生成TypeScript类型,而非手动复制请求/响应结构。使用服务端状态库(例如TanStack Query),保证加载/错误/重试逻辑统一。只做一次错误映射(单个函数),并在错误UI中展示服务端
parseApiError,方便用户反馈与服务端日志对齐。request_id
Checklist (when enforcing)
(推行规范时的)检查清单
- Naming matches project (camelCase/PascalCase/snake_case)
- No direct mutation of arguments or shared state
- Errors handled and propagated with context
- No unnecessary ; types explicit at boundaries
any - Public APIs documented (the language's doc-comment format, or the project standard)
- Files and structure match existing layout
- No magic numbers; constants named
- Lint and format rules pass (if project has them)
- 命名符合项目约定(camelCase/PascalCase/snake_case)
- 没有直接修改参数或共享状态
- 错误得到处理,并携带上下文传播
- 没有不必要的;边界处类型明确
any - 公共API有文档(遵循语言的文档注释格式或项目标准)
- 文件与结构符合现有布局
- 没有魔法数字;常量已具名
- Lint和格式规则通过(如果项目有配置)
Anti-patterns
反模式
| Anti-pattern | Better approach |
|---|---|
| "It's just a small script" | Apply same naming and structure; future readers will thank you |
| Commenting out code "for later" | Delete; use git history or a ticket |
| Fixing only the file in scope | If touching a pattern, suggest project-wide convention or follow-up |
| Adding style rules without tooling | Put them in the language's formatter and linter so format is automatic ( |
| 反模式 | 更好的做法 |
|---|---|
| “这只是个小脚本” | 应用相同的命名和结构规范;未来的读者会感谢你 |
| 把代码注释掉“以后用” | 删掉;用git历史或工单记录 |
| 只修复当前范围内的文件 | 如果涉及某种模式,建议推行项目级规范或安排后续工作 |
| 只加风格规则不配套工具 | 把规则放进语言的格式化工具和linter里,实现自动格式化( |
Integration
集成说明
- If the project has a style guide, CONTRIBUTING, or lint/format config, align with it first. Override only when the user explicitly asks.
- Suggest concrete edits (rename, extract function, add type) rather than only listing rules.
- 如果项目有风格指南、CONTRIBUTING文档或lint/格式化配置,优先对齐。仅在用户明确要求时才覆盖。
- 给出具体的修改建议(重命名、抽取函数、添加类型),而非仅仅罗列规则。