构建代码提交规范-husky、Eslint和Prettier的简单使用

365 阅读6分钟

在团队协作开发中,代码的提交规范和代码质量控制是确保项目代码质量和可维护性的重要环节。本文将介绍如何通过工具和配置来实现代码提交规范化和代码质量的控制,涵盖了 commitlint、lint-staged、husky、Prettier 和 ESLint 等工具的使用与配置。

本文对于Eslint将主要介绍在eslint.config.js 文件的配置,对于以前的使用有相似之处

1. 什么是 commitlint?

commitlint 是用于设置代码提交规范的工具。它可以帮助团队在代码提交阶段规范化提交信息的格式和内容,提高代码可读性和可维护性。通过 commitlint 的配置,我们可以定义提交信息的格式、校验规则和错误提示等内容,确保代码提交的质量符合团队和项目的要求。

1.1 安装配置 commitlint

首先,使用 pnpm 进行安装 commitlint 和相关配置:

pnpm add --save-dev @commitlint/{cli,config-conventional}

安装完成后,执行以下命令配置 commitlint:

echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js

这会在根目录下创建 commitlint.config.js 文件,其中包含了基本的配置信息,例如:

module.exports = {
    extends: ['@commitlint/config-conventional'],
};

当然你也可能需要更多的配置操作,例如一些自定义的规则,下面只是简单的举例,具体看自己的需要,官网上还有更多详细的规则及介绍:

module.exports = {
    extends: [
        "@commitlint/config-conventional"
    ],
    // 以下是我们自定义的规则
    rules: {
        'type-enum': [
            2,
            'always',
            [
                'bug', // 此项特别针对bug号,用于向测试反馈bug列表的bug修改情况
                'feat', // 新功能(feature)
                'fix', // 修补bug
                'docs', // 文档(documentation)
                'style', // 格式(不影响代码运行的变动)
                'refactor', // 重构(即不是新增功能,也不是修改bug的代码变动)
                'test', // 增加测试
                'chore', // 构建过程或辅助工具的变动
                'revert', // feat(pencil): add ‘graphiteWidth’ option (撤销之前的commit)
                'merge' // 合并分支, 例如: merge(前端页面): feature-xxxx修改线程地址
            ]
        ]
    }
};

2. 使用 lint-staged

lint-staged 的主要作用是在 Git 提交之前对暂存区(即即将提交的文件)中的文件执行指定的任务,常见的任务包括代码风格检查、格式化、语法检查等。通过配置 lint-staged,开发者可以在提交代码之前自动运行这些任务,从而避免提交不符合规范的代码。

2.1 安装 lint-staged

使用以下命令安装 lint-staged:

pnpm add --save-dev lint-staged

2.2 配置 lint-staged

在根目录下创建 .lintstagedrc 文件,配置需要在提交前进行的代码检查和格式化操作:

{ 
    "src/**/*.{ts,vue}": [ 
        "prettier --write", 
        "eslint --fix" 
    ]
}

3. 安装配置 husky

Husky 是一个用于设置 Git 钩子的工具,可以在代码提交前执行预定义的命令。

3.1 安装 husky

使用 pnpm 进行 husky 的安装:

pnpm add --save-dev husky

然后执行以下命令初始化 husky:

pnpm exec husky init

3.2 配置 husky

更新 pre-commit 钩子内容,执行 lint-staged:

echo "pnpm lint-staged" > .husky/pre-commit

创建 commit-msg 钩子文件,并填写内容:

echo "pnpm dlx commitlint --edit $1" > .husky/commit-msg

4. Prettier

Prettier 的主要作用是对代码进行自动化的格式化和风格调整,通过提供统一的代码格式化风格来简化代码维护和协作,减少开发人员在代码风格上的争议,从而提高代码的可读性和可维护性。

4.1 安装配置 Prettier

使用 pnpm 安装 Prettier:

pnpm add --save-dev --save-exact prettier

在使用 Prettier 和 ESLint 结合时,还需安装以下两个插件: eslint-plugin-prettiereslint-config-prettier 这两个插件的主要作用是确保 ESLint(代码检查工具)与 Prettier(代码格式化工具)能够完美配合,同时避免二者之间的冲突和重复的工作。

eslint-plugin-prettier 的主要作用是将 Prettier 的格式化功能集成到 ESLint 中。具体来说,它会将 Prettier 的格式化能力作为 ESLint 的一个规则进行执行,从而在代码检查的同时自动格式化代码。

eslint-config-prettier 的主要作用是禁用 ESLint 中与 Prettier 重复或冲突的规则,从而避免二者之间的冲突和重复工作。

pnpm add --save-dev eslint-plugin-prettier eslint-config-prettier

对于插件配置在 eslint.config.js 文件中的使用有相应调整

***
import eslintConfigPrettier from "eslint-config-prettier"; 
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'; 
***
export default [ 
    *** 
    eslintPluginPrettierRecommended, 
    eslintConfigPrettier, 
    ***
]

创建 .prettierrc 文件,并配置美化规则:

{
  "tabWidth": 4,
  "useTabs": true,
  "printWidth": 120,
  "singleQuote": true
}

5. Eslint

ESLint 的主要作用是通过检查代码中的语法、代码风格和潜在的错误,帮助开发人员编写更加规范和高质量的代码。

初始化eslint,需要本地有 package.json 文件,然后执行命令

npm init @eslint/config@latest

以vue3为例,对eslint进行安装 整个过程可能包含的提问如下:

  1. How would you like to use ESLint? · To check syntax, find problems, and enforce code style (选择如何使用 ESLint,检查语法、找出问题和强制执行代码风格)
  2. What type of modules does your project use? · JavaScript modules (import/export)
  3. Which framework does your project use? · Vue.js
  4. Does your project use TypeScript? · Yes
  5. Where does your code run? · Browser
  6.  Which style guide do you want to follow? · Standard: github.com/standard/es…
  7.  Would you like to install them now? · Yes

安装完成之后,会在根目录下生成一个 eslint.config.js 文件

对于 eslint.config.js 中的配置,需要进行一些改写,对于包含TypeScript的项目,需要单独安装 typescript-eslint

pnpm add --save-dev typescript-eslint

然后在 eslint.config.js 文件中添加:

*** 
import tseslint from 'typescript-eslint'; 
... 
export default [
    *** 
    ...tseslint.configs.recommended, 
    *** 
]

vue结合typescript的项目,对于eslint的 parser 的添加,在 eslint.config.js 中的配置与之前不同,需要单独引入parser的函数

***
import vueEslintParser from 'vue-eslint-parser'; 
import typescriptParser from '@typescript-eslint/parser'; 
***
export default [ 
    { 
        languageOptions: { 
            parser: vueEslintParser, 
            parserOptions: { 
                parser: typescriptParser, 
            } 
        }, 
    } 
]

下面是一个简单的 eslint.config.js 文件,代码如下:

import globals from "globals";
import pluginVue from "eslint-plugin-vue";

// import path from "path";
// import { fileURLToPath } from "url";
// import { FlatCompat } from "@eslint/eslintrc";
import pluginJs from "@eslint/js";

import eslintConfigPrettier from "eslint-config-prettier";
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';

import tseslint from 'typescript-eslint';

import vueEslintParser from 'vue-eslint-parser';
import typescriptParser from '@typescript-eslint/parser';

// mimic CommonJS variables -- not needed if using CommonJS
// const __filename = fileURLToPath(import.meta.url);
// const __dirname = path.dirname(__filename);
// const compat = new FlatCompat({ baseDirectory: __dirname, recommendedConfig: pluginJs.configs.recommended });

export default [
    { languageOptions: { globals: globals.browser } },
    // ...compat.extends("standard-with-typescript"),
    pluginJs.configs.recommended,
    ...pluginVue.configs["flat/essential"],
    ...tseslint.configs.recommended,
    eslintPluginPrettierRecommended,
    eslintConfigPrettier,
    {
        languageOptions: {
            parser: vueEslintParser,
            parserOptions: {
                parser: typescriptParser,
            }
        },
        rules: {
            "no-unused-vars": "warn",
            "no-undef": "off",
            "linebreak-style": ["error", "unix"],
            "semi": ["error", "always"],
            "vue/multi-word-component-names": "off",
            "vue/no-multiple-template-root": "off",
            "@typescript-eslint/no-explicit-any": "off"
        }
    }
];

以上就是一套简单的代码提交规范和代码质量控制流程的实践配置。这些工具和配置,有很多属性规则和配置要求,可以根据自己的需要,在官网上查找自己需要的配置。