web-master
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWeb Master
Web 开发规范
Follow these instructions when writing web-related code.
编写 Web 相关代码时,请遵循以下说明。
TypeScript
TypeScript
Do not use type assertions
不要使用类型断言
Do not reach for type assertions unless you need one. Never add a type assertion up front because you think you might need it later. You may use a type assertion only when all of these conditions apply:
- You first write the code without a type assertion and encounter a type error.
- You cannot resolve that type error by improving type definitions elsewhere.
- Adding the type assertion does not compromise type safety.
除非确有需要,否则不要使用类型断言。不要因为觉得以后可能需要,就提前添加类型断言。只有同时满足以下所有条件时,才可以使用类型断言:
- 你先在没有类型断言的情况下编写代码,并遇到了类型错误。
- 无法通过改进其他位置的类型定义来解决该类型错误。
- 添加类型断言不会损害类型安全。
Do not use ReturnType
ReturnType不要使用 ReturnType
ReturnTypeDo not use unless you need it. Use the following approaches instead.
ReturnTypeIf you need to use the return type of a specific function defined in the project somewhere other than that function:
- For a simple primitive type such as or
boolean, write the type directly.string - For a complex type, define a named type, specify it as the function's return type (), and reuse
(): T => {}.T
If you need the return type of a library function:
- Check the function's type definitions first.
- If the library exports that type, use the exported type.
- If you need to pass the return type of another library function as a type argument and the library does not export that function's return type, you may use inside the type argument.
ReturnType
- If you need to pass the return type of another library function as a type argument and the library does not export that function's return type, you may use
- If the library does not export the type:
- Write the type directly if it is a simple primitive type.
- Otherwise, you may use .
ReturnType
ts
// Incorrect
import foo from "foo";
const myFunc = (): string => {...};
const myFunc2 = (arg: ReturnType<typeof foo>, arg2: ReturnType<typeof myFunc>): number => {...};
// Correct
import type { FooResult } from "foo";
const myFunc = (): string => {...};
const myFunc2 = (arg: FooResult, arg2: string): number => {...};除非确有需要,否则不要使用 。请改用以下方式。
ReturnType如果需要使用项目中其他地方定义的特定函数的返回类型:
- 对于 或
boolean等简单原始类型,请直接写出该类型。string - 对于复杂类型,请定义一个具名类型,将其指定为函数的返回类型(),然后复用
(): T => {}。T
如果需要使用库函数的返回类型:
- 首先检查该函数的类型定义。
- 如果库导出了该类型,请使用导出的类型。
- 如果需要将另一个库函数的返回类型作为类型参数传入,但该库没有导出这个函数的返回类型,则可以在类型参数中使用 。
ReturnType
- 如果需要将另一个库函数的返回类型作为类型参数传入,但该库没有导出这个函数的返回类型,则可以在类型参数中使用
- 如果库没有导出该类型:
- 如果是简单原始类型,请直接写出该类型。
- 否则,可以使用 。
ReturnType
ts
// Incorrect
import foo from "foo";
const myFunc = (): string => {...};
const myFunc2 = (arg: ReturnType<typeof foo>, arg2: ReturnType<typeof myFunc>): number => {...};
// Correct
import type { FooResult } from "foo";
const myFunc = (): string => {...};
const myFunc2 = (arg: FooResult, arg2: string): number => {...};Prefer as const satisfies
over type annotations
as const satisfies优先使用 as const satisfies
,而不是类型注解
as const satisfiesDo not add type annotations unless you need them. Start by writing the code without a type annotation. If that causes a type error, first try to resolve it by improving type definitions elsewhere. Use a type annotation only as a last resort when those changes cannot solve the problem.
When you write an object and need to guarantee that it conforms to a specific type, use . If the object will not change, also use . You don't need to use on temporary arrays used inline, or on values whose type is obvious, such as arrays of strings. Also, you don't need to specify for the type of an value.
satisfiesas constas constsatisfiesReadOnlyas const satisfiests
// Incorrect
const foo: T = {
bar: "bar"
};
const foo = {
bar: "bar"
} as const satisfies ReadOnly<T>;
// Correct
const foo = {
bar: "bar"
} as const satisfies T;除非确有需要,否则不要添加类型注解。首先尝试在不使用类型注解的情况下编写代码。如果因此出现类型错误,应先尝试通过改进其他位置的类型定义来解决。只有当这些更改仍无法解决问题时,才将类型注解作为最后手段。
当你编写对象并需要保证其符合特定类型时,请使用 。如果对象不会发生变化,还应同时使用 。对于内联使用的临时数组,无需使用 ;对于类型显而易见的值(如字符串数组),也无需使用 。此外,对于 值的类型,无需指定 。
satisfiesas constas constsatisfiesas const satisfiesReadOnlyts
// Incorrect
const foo: T = {
bar: "bar"
};
const foo = {
bar: "bar"
} as const satisfies ReadOnly<T>;
// Correct
const foo = {
bar: "bar"
} as const satisfies T;Do not disable ESLint rules
不要禁用 ESLint 规则
Do not disable ESLint rules as an easy workaround. ESLint errors usually identify low-quality code rather than create pointless obstacles. Disabling a rule to silence an error leaves the underlying problem in place.
Disable an ESLint rule only as a last resort when no better option exists. Handle ESLint errors as follows:
- Understand what ESLint is reporting. Identify the affected code and the purpose behind the rule.
- Improve the code in a way that addresses that purpose.
- Disable the rule only when complying with it would make the code excessively complex, the warning is a clear false positive, you have another legitimate reason to disable it, or a possible fix would conflict with the rule's underlying intent.
不要把禁用 ESLint 规则当作便捷的解决方案。ESLint 错误通常是在指出低质量代码,而不是制造毫无意义的障碍。禁用某条规则来消除错误,只会掩盖其背后的问题。
只有在没有任何更好的选择时,才应禁用 ESLint 规则。处理 ESLint 错误时应遵循以下步骤:
- 理解 ESLint 报告的内容。确定受影响的代码以及该规则的目的。
- 通过改进代码来满足该规则的目的。
- 仅当遵守规则会使代码过度复杂、警告明显属于误报、你存在其他合理理由需要禁用规则,或者可能的修复方案会与该规则的基本意图冲突时,才禁用该规则。
Examples
示例
The ESLint rule defines a consistent import order. In properly modularized code, behavior should not depend on import order, so you should follow the rule.
sort-importsts
// Incorrect
/* eslint-disable sort-imports */
import foo from "foo";
import bar from "bar";
// Correct
import bar from "bar";
import foo from "foo";The rule exists to give numeric values meaningful names when their purpose would otherwise be unclear. You do not need to force an obvious value, such as when it represents the number of seconds in a minute, into a constant just to satisfy the rule. In that case, disabling the rule is acceptable. Replacing with a constant named also defeats the purpose of . Give the value a meaningful name instead, or disable the rule if its meaning is already obvious. Also consider whether the number needs to be hard-coded in the first place.
no-magic-numbers601ONEno-magic-numbersts
// Incorrect
// eslint-disable-next-line no-magic-numbers
if (myArray.length !== 0) {...}
// Correct
if (myArray.length) {...}The and rules exist as indicators of code readability and maintainability. Warnings for these rules suggest that your code design may be poor. Simply removing line breaks to meet the rules is a superficial solution and actually makes the code harder to read, thus violating the essence of the rules. Instead, you should fix the problem by removing redundant code or properly restructuring and modularizing it. If you've only slightly exceeded the limit and your code is already well-designed, you should disable the rules rather than removing line breaks or forcing splits.
max-linesmax-lines-per-functionESLint 的 规则用于定义一致的导入顺序。在正确模块化的代码中,行为不应依赖导入顺序,因此应遵循该规则。
sort-importsts
// Incorrect
/* eslint-disable sort-imports */
import foo from "foo";
import bar from "bar";
// Correct
import bar from "bar";
import foo from "foo";no-magic-numbers601ONEno-magic-numbersts
// Incorrect
// eslint-disable-next-line no-magic-numbers
if (myArray.length !== 0) {...}
// Correct
if (myArray.length) {...}max-linesmax-lines-per-functionDo not validate it yourself
不要自行进行验证
TypeScript types are not just an afterthought to JavaScript. Designing with types in mind keeps your code clean and efficient. With proper type design, validation is rarely needed except at project boundaries such as user input or web API responses. When code is properly designed based on types, function inputs and outputs are reliable, eliminating the need to validate values repeatedly.
Check the project dependencies to see if a validation library is installed. If one is installed, you should leverage the library's features rather than writing your own validator.
ts
// Incorrect
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
const isParson = (value: unknown): value is Person => isRecord(value) && typeof value.name === "string" && typeof value.age === "number" && value.age >= 0;
isParson(externalValue) ? externalValue : "Unknown";
// Correct
import { type } from "arktype";
const Person = type({
name: "string",
age: "number >= 0"
});
const parsed = Person(externalValue);
parsed instanceof type.errors ? "Unknown" : parsed;TypeScript 类型并不是 JavaScript 完成后的补充。围绕类型进行设计可以让代码保持简洁高效。类型设计合理时,通常很少需要额外验证,只有在项目边界处,例如处理用户输入或 Web API 响应时才需要验证。当代码基于类型进行了合理设计时,函数的输入和输出就是可靠的,无需反复验证这些值。
检查项目依赖项中是否安装了验证库。如果已经安装,应利用该库提供的功能,而不是自行编写验证器。
ts
// Incorrect
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
const isParson = (value: unknown): value is Person => isRecord(value) && typeof value.name === "string" && typeof value.age === "number" && value.age >= 0;
isParson(externalValue) ? externalValue : "Unknown";
// Correct
import { type } from "arktype";
const Person = type({
name: "string",
age: "number >= 0"
});
const parsed = Person(externalValue);
parsed instanceof type.errors ? "Unknown" : parsed;CSS
CSS
Define only the necessary styles
仅定义必要的样式
When writing CSS, first check if a reset CSS is loaded into your project and if that reset CSS is applied to the page or layout file you are currently working on. If a reset CSS is in place, you do not need to define styles that overlap with it, such as (this is an example, but not limited to this).
margin: 0In CSS, you should only specify properties that need to be changed from the parent element, and you should not specify properties that do not need to be changed again. Remember that CSS has inheritance, and style accordingly.
css
/* reset.css */
* {
margin: 0;
}css
/* style.css */
/* Incorrect */
h1 {
margin: 0;
font-weight: bold;
}
h1 div {
font-weight: bold;
}
/* Correct */
h1 {
font-weight: bold;
}编写 CSS 时,首先检查项目中是否加载了 reset CSS,以及当前正在处理的页面或布局文件是否应用了该 reset CSS。如果已经使用 reset CSS,就无需定义与其重复的样式,例如 (这只是示例,并不局限于此)。
margin: 0在 CSS 中,只应指定需要相对于父元素更改的属性,不应再次指定无需更改的属性。请记住 CSS 具有继承性,并据此设置样式。
css
/* reset.css */
* {
margin: 0;
}css
/* style.css */
/* Incorrect */
h1 {
margin: 0;
font-weight: bold;
}
h1 div {
font-weight: bold;
}
/* Correct */
h1 {
font-weight: bold;
}Intentional typography design
有意图的排版设计
Do not specify outside the document root unless absolutely necessary, such as in code blocks. Also, as a general rule, do not change the font size unless there is a clear reason, such as making unimportant notices smaller or headings larger. Since the base font size may be overridden by browser settings, use or instead of for font size or areas that depend on font size.
font-familyemrempxcss
/* Incorrect */
h1 {
font-size: 32px;
}
/* Correct */
h1 {
font-size: 2rem;
}除非绝对必要,否则不要在文档根元素之外指定 ,代码块等场景除外。此外,作为一般原则,除非有明确原因,例如缩小次要提示文字或放大标题,否则不要修改字体大小。由于浏览器设置可能会覆盖基础字号,因此字号或依赖字号的区域应使用 或 ,而不是 。
font-familyemrempxcss
/* Incorrect */
h1 {
font-size: 32px;
}
/* Correct */
h1 {
font-size: 2rem;
}HTML and JSX
HTML 和 JSX
Avoid redundant definitions
避免冗余定义
If a UI component library is available, actively use its components and reduce custom implementations unless absolutely necessary.
Also, avoid adding unnecessary attributes. For example, icon component libraries may have set by default; in such cases, there's no need to set this attribute again when using the component.
aria-hidden如果项目中提供了 UI 组件库,应积极使用其组件,并减少自定义实现,除非绝对必要。
此外,避免添加不必要的属性。例如,图标组件库可能已经默认设置 ,这种情况下使用该组件时无需再次设置此属性。
aria-hiddenTesting
测试
Design tests properly
正确设计测试
Do not mock application-owned modules. Prefer real implementations and test observable behavior rather than implementation wiring. Use mocks only at slow, nondeterministic, destructive, or external boundaries. Avoid tests whose assertions only verify mock calls or values configured on mocks.
Test the behavior from an external perspective, not the internal implementation. In other words, tests that require changes when refactoring are bad tests. Test the project's code, not the browser or external libraries. For example, it's obvious that a button element will be displayed in the browser when you write it; this tests the browser's behavior, not the project's code.
不要 mock 应用自身的模块。应优先使用真实实现,并测试可观察行为,而不是实现之间的连接方式。仅在速度缓慢、不确定、具有破坏性或属于外部边界的情况下使用 mock。避免编写仅验证 mock 调用次数或 mock 配置值的断言。
应从外部视角测试行为,而不是测试内部实现。换言之,重构时需要同步修改的测试就是糟糕的测试。应测试项目自身的代码,而不是浏览器或外部库。例如,编写按钮元素后,浏览器显然会显示它;这种测试验证的是浏览器的行为,而不是项目的代码。
Do not export for testing purposes
不要为了测试而导出
You should not export functions, values, or other data solely for testing purposes. When testing things that are not used outside of the file except for testing, use in-source testing instead of exporting them and creating a separate test file.
不应仅仅为了测试而导出函数、值或其他数据。如果某些内容除测试外不会在文件外部使用,请使用 in-source testing,而不是将它们导出并创建单独的测试文件。
Do not mock the external environment
不要模拟外部环境
For tests that require access to databases or external servers, use Testcontainers instead of mocking them. If a timer is needed, use the fake timer from the test library.
对于需要访问数据库或外部服务器的测试,请使用 Testcontainers,而不是进行 mock。如果需要定时器,请使用测试库提供的 fake timer。