环境版本 OS: windows11 ESLint:9.0 node:22.9.0 Prettier:3.1.2 husky:9.1.7

ESLint 与 Prettier 配置

配置 ESLint 和 Prettier 有助于在于提升代码质量、统一代码风格、提高开发效率以及增强团队协作能力。ESLint 主要用于静态代码分析,能够检测代码中的潜在错误、不规范的写法以及不符合最佳实践的地方,从而帮助开发者提前发现问题并修复。Prettier 则专注于代码格式化,能够自动调整代码的缩进、换行、引号等格式细节,确保代码风格的一致性。本文档所有内容均以 vite 创建 React+TypeScript 项目为例
首先安装依赖,再修改下面两个文件的内容

1
npm install eslint prettier eslint-plugin-prettier eslint-config-prettier eslint-plugin-react --save-dev
  1. eslint.config.cjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const js = require("@eslint/js");
const globals = require("globals");
const reactPlugin = require("eslint-plugin-react");
const reactHooksPlugin = require("eslint-plugin-react-hooks");
const reactRefreshPlugin = require("eslint-plugin-react-refresh");
const tsParser = require("@typescript-eslint/parser");
const tsPlugin = require("@typescript-eslint/eslint-plugin");
const prettierPlugin = require("eslint-plugin-prettier");

module.exports = [
js.configs.recommended,
{
files: ["**/*.{js,jsx,ts,tsx}"], // 匹配所有 JS、JSX、TS 和 TSX 文件
languageOptions: {
ecmaVersion: "latest",
sourceType: "module",
globals: {
...globals.browser,
...globals.node,
},
parser: tsParser,
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
},
plugins: {
react: reactPlugin,
"react-hooks": reactHooksPlugin,
"react-refresh": reactRefreshPlugin,
"@typescript-eslint": tsPlugin,
prettier: prettierPlugin,
},
settings: {
react: {
version: "detect",
},
},
rules: {
...reactPlugin.configs.recommended.rules,
...reactHooksPlugin.configs.recommended.rules,
...tsPlugin.configs.recommended.rules,
"react-refresh/only-export-components": "warn",
"no-console": "warn",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "warn",
"react/react-in-jsx-scope": "off",
"react/jsx-no-target-blank": "warn",
},
},
];
  1. vite.config.ts
1
2
3
4
5
6
7
8
9
10
11
12
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import eslintPlugin from 'vite-plugin-eslint';

export default defineConfig({
plugins: [
react(),
eslintPlugin({
include: ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.js', 'src/**/*.jsx'], // 检查 src 目录下的 TS、TSX、JS 和 JSX 文件
}),
],
});
  1. 在 package.json 文件里面对 script 字段进行修改,其他内容保持不变
1
2
3
4
5
6
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"lint:fix": "eslint . --fix"
},
  1. 安装 Prettier - Code formatter 插件
  2. 打开 VSCode 的设置:
    通过菜单:文件 > 首选项 > 设置。
    在搜索框中输入 format on save,找到 Editor: Format On Save 选项并勾选。
    在搜索框中输入 default formatter,找到 Editor: Default Formatter 选项,选择 Prettier - Code formatter。此时保存文件时就可以自动完成 Prettier 检查和修正

Git 提交规范流程

规范代码提交能够提高代码库的质量和可管理性,还有助于促进团队的协作和效率

提交遵循的一些原则

  • 清晰描述每次 commit, 包含修改了什么和为什么这么修改。
  • 一次 commit 尽量最小化,它只做一件事,增量代码量尽量控制在 100 行以下。
  • 一次 commit 不应破坏编译,确保 commit 后系统运行良好。
  • 避免单独提交测试代码,测试代码用以验证代码功能,应该把它与代码提交到相同的 commit 中;独立的测试修改可以放到单独的 commit 中,比如为历史代码写单测,重构测试代码,引人测试框架代码等。

使用 Commitizen 规范化提交诉求

  1. 首先,你需要在项目中安装 Commitizen 和适配器(推荐全局安装)
    npm install -g commitizen cz-conventional-changelog
  2. 在项目的根目录下创建文件.cz-config.js (文件名必须是这个)
    在该文件内部添加以下内容(此部分代码后续可以根据需求灵活修改)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module.exports = {
prompter: (cz, commit) => {
cz.prompt([
{
type: 'list',
name: 'type',
message: '请选择提交类型:',
choices: [
{ value: 'feat', name: 'feat: 新功能' },
{ value: 'fix', name: 'fix: 修复' },
{ value: 'docs', name: 'docs: 文档变更' },
{ value: 'style', name: 'style: 代码格式(不影响代码运行的变动)' },
{ value: 'refactor', name: 'refactor: 重构(既不是增加feature, 也不是修复bug)' },
{ value: 'perf', name: 'perf: 性能优化' },
{ value: 'test', name: 'test: 增加测试' },
{ value: 'chore', name: 'chore: 构建过程或辅助工具的变动' },
{ value: 'revert', name: 'revert: 回退' },
{ value: 'build', name: 'build: 打包' }
]
},
{
type: 'input',
name: 'scope',
message: '请输入修改范围(可选):'
},
{
type: 'input',
name: 'subject',
message: '请简要描述提交(必填)',
validate: (input) => !!input || '提交描述不能为空!'
},
{
type: 'input',
name: 'body',
message: '请输入详细描述(可选)'
},
{
type: 'input',
name: 'footer',
message: '请输入要关闭的issue(可选)'
}
]).then((answers) => {
const { type, scope, subject, body, footer } = answers;

const commitMessage = `${type}${scope ? `(${scope})` : ''}: ${subject}\n\n${body || ''}\n\n${footer || ''}`;

commit(commitMessage.trim());
});
}
};

Commitizen 默认使用 CommonJS 模块系统来加载配置文件(如 .cz-config.js 或 .cz-config.cjs)。这是因为 Commitizen 是基于 Node.js 的工具,而 Node.js 在默认情况下使用 CommonJS 模块系统。因此需要把 package.json 中的”type”类型设置为”commonjs” 3. 更新 package.json
在 package.json 中,确保 Commitizen 的 path 配置指向

1
2
3
4
5
6
7
8
cz-config.js:
{
"config": {
"commitizen": {
"path": "./.cz-config.js"
}
}
}
  1. 完成提交信息
1
2
3
git init
git add .
git cz

使用 husky+commitlint 检查提交描述是否符合规范

commitlint

  1. 安装依赖
1
npm install --save-dev @commitlint/cli @commitlint/config-conventional//确保npm版本是7.x及以上
  1. 在项目创建 commmitlint.config.js 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
module.exports = {
//继承的规则
extends: ['@commitlint/config-conventional'],
rules: {
// type 类型定义,表示 git 提交的 type 必须在以下类型范围内
'type-enum': [
2,
'always',
[
'feat', // 新功能 feature
'fix', // 修复 bug
'docs', // 文档注释
'style', // 代码格式(不影响代码运行的变动)
'refactor', // 重构(既不增加新功能,也不是修复bug)
'perf', // 性能优化
'test', // 增加测试
'chore', // 构建过程或辅助工具的变动
'revert', // 回退
'build' // 打包
]
],
// subject 大小写不做校验
'subject-case': [0]
}
};

注意:确保保存格式为UTF-8,否则可能会出错

安装 husky

  1. 在项目中安装 husky
1
npm install --save-dev husky
  1. 初始化 husky
1
npx husky init

这会在项目根目录下创建一个 .husky 文件夹,用于存放 Git Hooks 3. 执行 prepare 指令

1
npm run prepare
  1. 添加 commitint 的 hook 到 husky 中
    在.husky 目录下创建文件 commit-msg,文件内容如下
1
2
#!/usr/bin/env sh
npx --no -- commitlint --edit "$1"

必须注意的是确保文件使用 Unix 换行符(LF),而不是 Windows 换行符(CRLF)使用 VSCode 打开文件,点击右下角的 CRLF,然后选择LF。以及编码格式必须选择UTF-8
那么至此,我们已经处理好了强制规范化的提交要求,不符合规定的提交信息将不可再被提交!

通过 pre-commit 检测提交时的代码规范

虽然我们已经通过配置 ESLint 和 Prettier 确保了代码的规范性,但这只是本地的,无法仿制提交的代码不符合规范,所以需要规避这种风险
在.husky 目录下新建 pre-commit 文件

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/sh

# 运行 ESLint 检查
echo "Running ESLint..."
npx eslint --fix src/

# 运行 Prettier 格式化代码
echo "Running Prettier..."
npx prettier --write src/

# 将修复后的代码添加到暂存区
git add .

任务搞定~