husky + lint-staged + commitlint + prettier + changlog 前端规范化

173 阅读3分钟

1. 为什么要实施规范化

前端团队在开发时,经常会出现不同的开发习惯和代码风格,这样会影响代码的可维护性和可读性,造成代码质量不高的问题。

2. 实施规范化的好处

  1. 统一团队开发规范:统一代码风格,减少因不同风格引起的问题。
  2. 提高代码质量:可以有效减少代码的bug和错误,提高代码的可维护性和可读性。
  3. 提高开发效率:自动进行代码规范检查、代码格式化等处理,减少因手动错误导致的重复工作和时间浪费,同时提高开发效率。
  4. 降低维护成本。

3. 如何实现规范化

1. 安装依赖

主要用途:

  1. 格式化代码(ts,html,scss)
  2. commit提交规范校验
  3. 自动生成CHANGELOG
插件用途配置文件
huskygit hooks-
lint-stagedpre-commit辅助校验.lintstagedrc.json
prettier代码格式化.prettierrc.json
commitlintgit提交校验.commitlintrc.js
@commitlint/config-conventionalgit提交辅助,commitlint的校验规则-
commitizengit提交辅助-
cz-conventional-changeloggit提交辅助,如果需要在项目中使用commitizen生成符合AngularJS规范的提交说明,初始化cz-conventional-changelog适配器-
standard-versionchangelog自动生成-

安装依赖:npm i -D husky @commitlint/config-conventional commitizen cz-conventional-changelog commitlint lint-staged prettier standard-version

2. 根目录添加配置文件

  1. commitlint:.commitlintrc.js
module.exports = {
  extends: ['@commitlint/config-conventional']
};
  1. lint-staged:.lintstagedrc.json
{
  "*.{html,js,ts,scss,css,jsx,tsx,md}": ["prettier --write src"]
}

  1. prettier:.prettierrc.json
{
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "none",
  "printWidth": 120,
  "htmlWhitespaceSensitivity": "strict",
  "endOfLine": "auto",
  "overrides": [
    {
      "files": ["*.html"],
      "options": {
        "parser": "html",
        "printWidth": 60,
        "wrapAttributes": "auto"
      }
    },
    {
      "files": ["*.ts"],
      "options": {
        "parser": "typescript"
      }
    },
    {
      "files": ["*.scss"],
      "options": {
        "parser": "scss"
      }
    }
  ]
}

3. husky初始化

  • 初始化git hooks:npx husky install
  • package.json中添加script: "prepare": "husky install"
  • 创建pre-commit hook(用于校验git提交之前格式化):npx husky add .husky/pre-commit "npm run lint-staged"
  • 创建commit-msg hook(用于校验git提交信息格式): npx husky add .husky/commit-msg "npx --no -- commitlint --edit "$1""
  • 创建pre-push hook(用于git提交创建changelog): npx husky add .husky/pre-push "npm run release"

4. 更新 package.json

  • 添加scripts
"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "prepare": "husky install",
    "commit": "cz",
    "lint-staged": "lint-staged""release": "standard-version"
}
  • 添加config
"config": {
    "commitizen": {
      "path": "./node_modules/cz-conventional-changelog"
    }
  }

5. 使用

git提交代码使用命令 npm run commit

flow.png

6. commit提交规范解读

目前最为流行的提交信息规范来自于 Angular 团队。

规范中,主要就是要求提交内容要进行分类并填写内容,更为严格的规定是要求标注开发模块。

type:commit 的类型,有以下类型

  • feat:新功能、新特性;
  • fix: 修改 bug;
  • perf:更改代码,以提高性能;
  • refactor:代码重构(重构,在不影响代码内部行为、功能下的代码修改);
  • docs:文档修改;
  • style:代码格式修改, 注意不是 css 修改(例如分号修改代码换行等);
  • test:测试用例新增、修改;
  • build:影响项目构建或依赖项修改;
  • revert:恢复上一次提交;
  • ci:持续集成相关文件修改;
  • chore:其他修改(不在上述类型中的修改);