Skip to content

代码风格规范

eslint-config

Anthony 的 @antfu/eslint-config ESLint 配置集

使用 CLI 工具来设置项目,或者升级成扁平化配置。

sh
pnpm dlx @antfu/eslint-config@latest

配置 eslint.config.ts 文件

js
import antfu from '@antfu/eslint-config'

export default antfu()

第一层约束: IDE

VS Code 安装 ESLint 插件,这样你就可以在编辑器中实时看到代码风格的错误

第二层约束: Git Hooks

如果你想在每次提交之前进行代码效验并自动修复,你可以在 package.json 中添加以下内容:

json
{
  "scripts": {
    "lint": "eslint .",
    "lint:fix": "eslint . --fix"
  },
  "simple-git-hooks": {
    "pre-commit": "pnpm lint-staged"
  },
  "lint-staged": {
    "*": "eslint --fix"
  }
}

安装 simple-git-hookslint-staged

sh
pnpm add simple-git-hooks lint-staged -D
  • simple-git-hooks:可以让你方便的添加 git hook
  • lint-staged:只检验 git 工作区的文件,不会导致你一下出现成百上千个错误

激活 simple-git-hooks,更新 ./git/hooks

sh
npx simple-git-hooks

第三层约束: CI

git hooks 可以绕过,但 CI(持续集成) 是绝对绕不过的,因为它在服务端校验。使用 github CI 做持续集成,配置文件 .github/workflows/ci.yml 如下所示

yml
name: CI

on:
  push:
    branches:
      - main
    tags-ignore:
      - '*'

  pull_request:
    branches:
      - main

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install pnpm
        uses: pnpm/action-setup@v4

      - name: Set node
        uses: actions/setup-node@v4
        with:
          node-version: lts/*
          cache: pnpm

      - name: Install
        run: pnpm install

      - name: Lint
        run: pnpm run lint

Reference