编码规范
代码组织
- 单一职责:每个源文件应有清晰且聚焦的作用范围/目的
- 拆分大文件:当文件变得庞大或处理过多职责时,应进行拆分
- 类型分离:始终将类型和接口分离到
types.ts或types/*.ts中 - 常量提取:将常量移至专用的
constants.ts文件中
运行时环境
- 偏好同构代码:尽可能编写运行时无关的代码,使其在 Node、浏览器和 Worker 中都能正常工作
- 明确运行时标识:当代码特定于某个环境时,在文件顶部添加注释:
// @env node
// @env browser
TypeScript
- 显式返回类型:尽可能显式声明返回类型
- 避免复杂内联类型:将复杂类型提取到专用的
type或interface声明中
注释
- 避免不必要的注释:代码应能自解释
- 解释“为什么”而不是“怎么做”:注释应描述推理或意图,而非代码本身做了什么
测试 (Vitest)
- 测试文件:
foo.ts→foo.test.ts(同一目录) - 使用
describe/itAPI(而非test) - 对于复杂输出使用
toMatchSnapshot - 对于语言特定快照使用带显式路径的
toMatchFileSnapshot
工具选择
@antfu/ni 命令
| 命令 | 说明 |
|---|---|
ni | 安装依赖 |
ni <pkg> / ni -D <pkg> | 添加依赖 / 开发依赖 |
nr <script> | 运行脚本 |
nu | 升级依赖 |
nun <pkg> | 卸载依赖 |
nci | 干净安装 (pnpm i --frozen-lockfile) |
nlx <pkg> | 执行包 (npx) |
TypeScript 配置
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
}
}
ESLint 配置
// eslint.config.mjs
import antfu from '@antfu/eslint-config'
export default antfu()
完成任务时,运行 pnpm run lint --fix 来格式化代码并修复代码风格。
详细配置选项: antfu-eslint-config
Git Hooks
{
"simple-git-hooks": {
"pre-commit": "pnpm i --frozen-lockfile --ignore-scripts --offline && npx lint-staged"
},
"lint-staged": { "*": "eslint --fix" },
"scripts": {
"prepare": "npx simple-git-hooks"
}
}
pnpm Catalogs
在 pnpm-workspace.yaml 中使用命名分类进行版本管理:
| 分类 | 用途 |
|---|---|
prod | 生产依赖 |
inlined | 打包器内联依赖 |
dev | 开发工具(linter、打包器、测试) |
frontend | 前端库 |
避免使用默认分类。分类名称可根据项目需求调整。
参考资料
| 主题 | 说明 | 参考文档 |
|---|---|---|
| ESLint 配置 | 框架支持、格式化程序、规则覆盖、VS Code 设置 | antfu-eslint-config |
| 项目设置 | .gitignore、GitHub Actions、VS Code 扩展 | setting-up |
| 应用开发 | Vue/Nuxt/UnoCSS 约定和模式 | app-development |
| 库开发 | tsdown 打包、纯 ESM 发布 | library-development |
| 单体仓库 | pnpm workspaces、集中化别名、Turborepo | monorepo |