前端工程化-格式化-pre-commit


前端工程化-格式化

React项目

Pre-commit Hook,在git commit之前进行代码格式化

为了防止一些不规范的代码 commitpush到远端,我们可以在git命令执行前用一些钩子来检测并阻止。现在大前端主要有两种git钩子插件:husky(jquery与next.js都在用),pre-commit(antd在用)。

  1. 安装 prettier prettier 文档

    npm install --save-dev --save-exact prettier
    echo {}> .prettierrc.json 
    touch .prettierignore 
    
    • .prettierrc.json 中写入

      {
        "singleQuote": true, // 单引号
        "semi": false, // 分号
        "tabWidth": 2, // 制表符宽度
        "useTabs": false, // 使用制表符
        "bracketSpacing": true, // 对象属性添加 空格 { foo: 'aaa' }
        "arrowParens": "avoid",
        "printWidth": 200, // 代码换行长度
        "jsxBracketSameLine": true,
        "jsxSingleQuote": true
      }
      
    • .prettierignore 中写入

      # Ignore artifacts:
      build
      coverage
      
  2. 安装 Pre-commit Hook

    npx mrm lint-staged
    

    这时在package.json中会多出一些字段

    "devDependencies": {
      "husky": ">=6",
      "lint-staged": ">=10",
      "prettier": "2.5.1"
    },
    "lint-staged": {
      "*.{js,css,md}": "prettier --write"
    }
    

    lint-staged中另添加文件类型ts,tsx,js,jsx "*.{js,css,md,ts,tsx,js,jsx}": "prettier --write"

    npx mrm lint-staged不成功出现错误,可能是因为:

    • 没有把prettier添加到 devDependencies: 重新安装

    • node 版本太低,升级node版本

      n模块是专门用来管理nodejs的版本,

      • 安装n模块:npm install -g n
      • 把当前系统的 Node 更新成最新的 “稳定版本”: n stable
  3. 安装 eslint-config-prettier

    npm i eslint-config-prettier --save-dev
    

    package.jsoneslintConfig规则中添加 prettier规则,放在后面,覆盖一部分的eslint规则

    "eslintConfig": {  "extends": [    "react-app",    "react-app/jest"  ]}
    
    "eslintConfig": {  "extends": [    "react-app",    "react-app/jest",    "prettier"  ]}
    

commitlint: 规范化 commit message的内容

  1. 安装 commitlint: commitlint 文档
# Install and configure if needed
npm install --save-dev @commitlint/{cli,config-conventional}
# For Windows:
npm install --save-dev @commitlint/config-conventional @commitlint/cli

# Configure commitlint to use conventional config
echo "module.exports = { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js

# Active hooks
npx husky install
# or
yarn husky install

# Add hook
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'
# or
yarn husky add .husky/commit-msg 'yarn commitlint --edit $1'

commitlint规范:

commit message: feat: add login

类型 描述
build 编译相关的修改,例如发布版本、对项目构建或者依赖的改动
chore 其他修改, 一些日常工作,比如将表格详情改为详情
ci 持续集成修改
docs 文档修改
feat 新特性、新功能
fix 修改bug
perf 优化相关,比如提升性能、体验
refactor 代码重构
revert 回滚到上一个版本
style 代码格式修改, 注意不是 css 修改
test 测试用例修改