在一个多人协作或长期维护的 Tauri 项目中,保持代码风格一致和提交历史清晰,远比“能用就行”重要得多。本节的三类规范并不复杂,但一旦养成习惯,就能大幅降低 Code Review 的摩擦,减少因风格争议产生的内耗。
前端:ESLint + Prettier
前端部分(React / Vue / Svelte 等)使用 ESLint 进行静态检查,Prettier 负责格式化。推荐配置一个共享的 .eslintrc.cjs 和 .prettierrc,并通过 lint-staged 在 git commit 前自动修复。
基础配置示例
在项目根目录安装:
npm install -D eslint prettier eslint-config-prettier eslint-plugin-vue @typescript-eslint/parser @typescript-eslint/eslint-plugin
.eslintrc.cjs 一个实用配置:
module.exports = {
root: true,
env: { browser: true, es2021: true },
parser: '@typescript-eslint/parser',
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:vue/vue3-recommended',
'prettier' // 必须放在最后,关闭与 Prettier 冲突的规则
],
rules: {
'no-console': 'warn',
'@typescript-eslint/no-explicit-any': 'warn'
}
}
配合 .prettierrc:
{
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100
}
在 package.json 的 scripts 中添加:
"lint": "eslint src --fix",
"format": "prettier --write src"
实战建议
- 把 ESLint 和 Prettier 检查集成到 CI 中,任何警告都会导致构建失败。
- 使用
husky+lint-staged在提交时仅检查暂存文件,避免全量扫描浪费时间。
Rust 端:Clippy + rustfmt
Rust 的代码规范有官方工具链强力支撑,几乎不存在“风格之争”。
rustfmt 负责自动格式化,安装 Tauri 后通常会跟随 Rust 环境一并提供。在项目根目录运行即可:
cargo fmt --all -- --check # CI 检查
cargo fmt --all # 手动格式化
Clippy 是 Rust 的官方 linter,能够捕捉大量常见错误、性能陷阱和不符合惯用写法的代码。运行方式:
cargo clippy --all-targets --all-features -- -D warnings
参数 -D warnings 会把所有 Clippy 警告视为错误,强烈建议在 CI 中使用。
进阶用法
在 src-tauri 目录下创建 clippy.toml 或直接在 Cargo.toml 中配置 lints。例如,禁用某个过于严格的规则:
[lints.clippy]
too_many_arguments = "allow"
实践要点
- 养成每次编译前运行
cargo clippy的习惯;可以在 VSCode 中安装 rust-analyzer 插件,它会实时显示 Clippy 提示。 - 在 CI 流程中,将
cargo fmt --check和cargo clippy -- -D warnings作为第一道门禁,失败则取消后续构建。
提交规范:Conventional Commits
混乱的 commit message(如 “update”、“fix bug”、“111”)是项目维护的噩梦。推荐采用 Conventional Commits 规范,格式为:
<type>[optional scope]: <description>
[optional body]
[optional footer]
常用 type
feat:新功能fix:Bug 修复docs:文档变更style:代码风格调整(不影响逻辑)refactor:重构(既不是新功能也不是修 Bug)test:添加或修改测试chore:构建流程、依赖、工具等的变更
示例
feat(window): add minimize-to-tray on close
fix(ipc): resolve file read crash on large files
docs: update build guide for Windows MSI
chore: bump tauri to 2.0.0-rc
辅助工具
commitlint可以配置在 husky 的 commit-msg 钩子中,自动校验提交信息格式。- 在 VSCode 中安装 Conventional Commits 插件,可生成合规的提交信息模板。
- ChangeLog 生成:结合
standard-version或semantic-release,可根据规范化的提交历史自动生成版本变更记录。
落地建议
在项目仓库根目录创建 .commitlintrc.js:
module.exports = {
extends: ['@commitlint/config-conventional']
}
然后在 package.json 配置 husky:
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
一句话总结:ESLint 和 Clippy 保证代码质量的门槛,Conventional Commits 保证协作历史的可读性。这三条规范不需要死记硬背,但一旦形成自动化检查流水线,整个团队的开发体验会有质的提升。