多人编写的项目需要做到代码风格统一,本文介绍如何实现在 git commit 时自动格式化代码,保证代码格式统一。

使用模块介绍:

  • prettier  代码格式化模块
  • husky  git的hook,在git 命令执行时执行中一些命令
  • lint-staged  对git暂存的文件进行lint检查
  • eslint   js代码检测工具

安装所有依赖:

yarn add --dev prettier husky lint-staged eslint

文件配置:

添加 .prettierrc 格式化配置文件,详细配置参考官方文档

{
  "singleQuote": true,
  "tabWidth": 2,
  "useTabs": false,
  "semi": false,
  "trailingComma": "all",
  "printWidth": 120,
  "bracketSpacing": true
}

添加 .eslinttrc.js 配置文件,详细配置参考官方文档

module.exports = {

  ...

  // add your custom rules here
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
  },
}

package.json 中增加 huskylint-staged 的配置,更多使用方法参考官方使用说明

"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,json,scss}": [
      "prettier --config .prettierrc --write",
      "eslint --fix",
      "git add"
    ]
  }

运行效果:

Some of your tasks use git add command. Please remove it from the config since all modifications made by tasks will be automatically added to the git commit index.

说明我们设置的 hooks 生效了,这样每次 commit 时都能自动检查和格式化代码了。