ESLint、Prettier、Husky 和 Commitlint 完美协作指南

326 阅读1分钟

1. ESLint

代码检查工具

主要是通过AST作词法分做和语法分析

  • 安装

pnpm add -D eslint

  • 创建配置文件

npm init @eslint/config

eslintrc.cjs文件

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:vue/vue3-essential',
    'prettier',
  ],
  overrides: [
    {
      files: ['.js', '.jsx', '.ts', '.tsx', '.vue', '.json'],
    },
  ],
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint', 'vue', 'prettier'],
  rules: {
    'prettier/prettier': 'error',
    'arrow-body-style': 'off',
    'prefer-arrow-callback': 'off',
  },
  ignorePatterns: ['node_modules/', 'dist/', 'pnpm-lock.yaml', '*.log'],
};

2. Prettier

代码格式化工具

主要是根据ESLint 规则进行格式化代码

  • 安装

pnpm add -D prettier

  • 创建配置文件 prettierrc.js
{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "printWidth": 80
}

3. 处理ESLint 和 prettier 冲突

  1. pnpm add -D eslint-config-prettier eslint-plugin-prettier

code.png

4. lint-staged

暂存区中运行指定脚本的工具 package.json中添加配置

"lint-staged": {
    "src/**/*.{js,jsx,ts,tsx,vue,json}": [
      "pnpm run format"
    ]
  }

5. Husky

Git hooks 管理工具

  • 启用git hooks

npx husky install,此时当前项目目录下创建一个.husky文件

  • 配置pre-commit git hooks

npx husky .husky/pre-commit "npx lint-staged"

6. commitlint

git commit message进行检查并格式统一

  • 项目中添加commit-msg git hooks
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
  • 创建配置文件

.commitlintrc.json 文件

{
  "extends": ["@commitlint/config-conventional"],
  "rules": {
    "scope-empty": [2, "never"],
    "type-empty": [2, "never"],
    "type-enum": [
      2,
      "always",
      [
        "wip",
        "feat",
        "merge",
        "fix",
        "test",
        "refactor",
        "build",
        "docs",
        "perf",
        "style",
        "ci",
        "chore",
        "workflow",
        "revert",
        "types",
        "release"
      ]
    ]
  }
}