项目规范CommitLint+ESLint+Prettier+StyleLint+LintStaged+Husky

644 阅读5分钟

ESLint

实践方案:

集成airbnb

  • pnpm i eslinit-config-airbnb
  • 然后在eslint的配置文件中直接集成airbnb
module.exports = {
    extends:'airbnb'
}

搭配Prettier灵活的定制

pnpm i -D eslint @eslint/create-config

  • @eslint/create-config是eslint初始化的命令行界面通过问题引导的形式进行配置;
  • npx eslint --init会进行引导配置相当于执行npx @eslint/create-config一般我们用来检查语法和提示问题,选择完成之后会生成对应的配置文件
  • 在项目脚本命令中添加eslint的脚本命令"lint:eslint":"eslint --cache --max-warning o {src,mock}/**/*.{vue,ts,tsx} --fix"--cache:只检查改动过的代码,0:如果超过0个警告强制eslint以错误状态退出
  • 根目录下创建eslint校验的忽略文件.eslintignore
node_modules
*.md
.vscode
.idea
dist
/public
/docs
.husky
.local
/bin
Dockerfile
  • 在项目里面添加vscode的工作区设置文件.vscode下的setting.json[在设置中打开command palette输入setting.json->open WorkSpace Settings(JSON )]内容添加下面代码,使编译器在保存的时候自动自动执行vscode扩展eslint去找项目里面的配置进行格式化
{
    "editor.codeActionOnSave":{
        "source.fixAll":true
    }
}
  • 最后不要忘记在编译器中安装eslint不然无法格式化 vscode中安装eslint扩展

Prettier

prettier自动化的代码格式化;

  • 安装pnpm i -D prettier
  • 添加prettier的配置文件,项目根目录.prettierrc.js内容
module.export = {
    printWidth:120,//但行长度
    tabWidth:4,//每个tab的空格
    useTabs:true, //使用空格代替tab缩进
    semi:true,//句末使用分号
    singleQuote:false,//使用单引号
    endOfLine:"auto",//
    trailingComma:"none"//对象最后一个末尾属性是否要逗号
}
  • package 添加执行命令"lint:prettier":"prettier --write **/*.{js,json,tsx,css,less,scss,vue,html,md}"

  • vscode里面安装 Prettier - Code formatter并修改Vscode的设置setting.json如下:

  "terminal.integrated.defaultProfile.windows": "Git Bash",
  "files.autoSave": "afterDelay",
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  • 解决eslint和prettier之间的冲突,需要安装pnpm i -D eslint-config-prettier eslint-plugin-prettier 其中config-prettier用来关闭eslint中与prettier冲突的规则,plugin-prettier让eslint用prettier的格式化代码的能力
  • 上述安装了plugin-prettier之后需要修改eslint的配置,在extends属性中添加'plugin:prettier/recommended'让eslint在对代码风格进行配置的时候只会使用prettier的配置
  • 在项目的根目录下创建不需要格式化的文件.prettierignore 添加内容
/dist/*
/node_modules/**

stylelint

stylelint是一个强大的样式检查工具,在保存时自动格式化样式文件,经常搭配插件:stylelint-order规范css属性顺序,减少回流次数;

  • 安装 pnpm i -D stylelint stylelint-config-standard安装官方推荐的配置
  • 安装其他的pnpm i -D stylelint-config-prettier stylelint-config-html stylelint-order stylelint-less postcss-html postcs-less stylelint-config-standard-vue[关闭与prettier的冲突配置,css样式的排序,支持检查html,less,vue项目推荐的配置]
  • 新建对应的配置文件.stylelintrc.json并添加内容
{
  "plugins": ["stylelint-order"],
  "ignoreFiles": [
    "**/*.js",
    "**/*.jsx",
    "**/*.tsx",
    "**/*.ts",
    "**/*.json",
    "**/*.md",
    "**/*.yaml"
  ],
  "rules": {
    "order/properties-order": [
      "position",
      "top",
      "right",
      "bottom",
      "left",
      "z-index",
      "display",
      "justify-content",
      "align-items",
      "float",
      "clear",
      "width",
      "min-width",
      "max-width",
      "height",
      "min-height",
      "max-height",
      "margin",
      "margin-top",
      "margin-right",
      "margin-bottom",
      "margin-left",
      "padding",
      "padding-top",
      "padding-right",
      "padding-bottom",
      "padding-left",
      "border",
      "border-width",
      "border-top-width",
      "border-right-width",
      "border-bottom-width",
      "border-left-width",
      "overflow",
      "overflow-x",
      "overflow-y",
      "font-size",
      "font-family",
      "text-align",
      "text-justify",
      "text-indent",
      "text-overflow",
      "text-decoration",
      "white-space",
      "color",
      "background",
      "background-position",
      "background-repeat",
      "background-size",
      "background-color",
      "background-clip",
      "border-style",
      "border-color",
      "border-top-style",
      "border-top-color",
      "border-right-style",
      "border-right-color",
      "border-bottom-style",
      "border-bottom-color",
      "border-left-style",
      "border-left-color",
      "border-radius",
      "opacity",
      "filter",
      "backdrop-filter",
      "list-style",
      "outline",
      "visibility",
      "box-shadow",
      "text-shadow",
      "resize",
      "transform",
      "transition",
      "cursor"
    ]
  }
}

  • 添加忽略文件.stylelintignore
/dist/*
/public/*
public/*
/mock/*
/node_modules/*
/plop-template/*
/types/*

husky

定义

Husky是一个Git钩子管理工具,它允许在特定的Git事件(commit,push)前运行自定义脚本,安装之后会在根目录生成.husky文件夹,这个文件夹是husky的核心,用于存放所有的git钩子脚本:

.husky/
├── pre-commit       # 提交前执行的脚本
├── pre-push         # 推送前执行的脚本
└── _/husky.sh       # Husky 的内部脚本,用于初始化环境

通常搭配 lint-staged 在package.json中注入githooks脚本,检查暂存区文件是否符合 Eslint 或 Prettier 规范并进行格式化处理来实现git仓库代码的统一性;

使用

安装配置步骤为:

  • 安装 pnpm install -D husky
  • 安装完成之后,在package里面添加命令 "prepare":"husky install"
  • 在控制台运行命令 pnpm run prepare会在项目的根目录下生成.husky 文件夹
  • 配置link-stage声明在哪些阶段需要进行代码提交的规范校验,安装 pnpm install -D lint-stage
  • 在package里面添加``` lint:lint-stage":"lint-staged"
  • 控制台运行 npx husky add .husky/pre-commit "npm run lint:lint-stage"在commit代码之前运行lint:lint-staged
  • lint-stage的配置在package中添加以下配置
"lint-staged":{
    "*.{js,jsx,ts,tsx}":[
        "eslint --fix",
        "prettier --write"
    ]
    "{!{package}*.json,*.code-snippets,.!{browserslist}*rc}":[
        "prettier --write--parse json"
    ]
    "package.json":[
        "prettier --write"
    ]
    "*.vue":[
        "eslint --fix",
        "prettier --write",
        "stylelint --fix"
    ]
    "*.{src,less,style,html}":[
        "stylelint --fix",
        "prettier --write"
    ],
    "*.md":[
        "prettier --write"
    ]
}
  • 规范commit的提交,安装 pnpm install -D @commitlint/cli @commitlint/config-conventional并在项目的根目录下创建.commitlintrc.js内容为
module.exports = {
    ignore: [(commit)=>commit.includes('int')]
    extends:['@commitlint/config-conventional']
    rules:{
        'body-leading-blank':[2,'always'],
        'footer-leading-blank':[2,'always'],
        'header-max-length':[2,'always',108],
        'subject-empty':[2,'never'],
        'type-empty':[2,'never'],
        'type-enum':[
            2,
            'always',
            [
                'feat',//新需求
                'fix',//改bug
                'perf',//优化项目性能
                'style',//样式更改
                'docs',//添加文档
                'test',//测试用例
                'refactor',//重构
                'build',//打包构建
                'ci',//自动部署配置
                'chore',//
                'revert',//重置代码 
                'wip',
                'workflow',//工作流
                'types',//类型
                'release'//发布新版本
            ]
        ]
    }
}
  • 添加脚本使👆生效 npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"之后的提交都需要符合commitlint格式:git commit -m "类型:描述"否则提交会失败;
    也可以修改commit-msg脚本如下:
# 运行 commitlint 检查
npx --no-install commitlint --edit "$1"

# 如果 commitlint 检查通过,则添加 emoji
if [ $? -eq 0 ]; then
  node "$(dirname "$0")/../scripts/update-commit-msg.js" "$1"
fi

在根目录创建scripts>update-commit-msg.js文件

const fs = require('fs')

const commitMsgFilePath = process.argv[2]
const commitMsg = fs.readFileSync(commitMsgFilePath, 'utf-8').trim()
const rules = [
  { type: 'feat', symbol: '✨' },
  { type: 'fix', symbol: '🐞' },
  { type: 'docs', symbol: '📝' },
  { type: 'style', symbol: '🎨' },
  { type: 'refactor', symbol: '📸' },
  { type: 'test', symbol: '🧪' },
  { type: 'chore', symbol: '🎓' },
  { type: 'revert', symbol: '💫' },
  { type: 'ci', symbol: '🤖' },
  { type: 'build', symbol: '🏭' }
]

let updatedCommitMsg = commitMsg
for (const rule of rules) {
  if (commitMsg.startsWith(`${rule.type}:`)) {
    updatedCommitMsg = `${rule.symbol} ${commitMsg}`
    break
  }
}

fs.writeFileSync(commitMsgFilePath, updatedCommitMsg)

这样我们提交的时候 husky 会检查提交信息并在检查通过后添加对应的emoji符号