IndieShow 图标IndieShow 使用文档

代码规范和格式化

如何在 IndieShow 项目中配置和使用 ESLint、Prettier 和 Git Hooks,实现代码质量检测、自动格式化和提交规范,提升团队协作效率和代码可维护性

代码规范和格式化

本指南将帮助你理解和配置 IndieShow 项目的代码规范、格式化工具和提交规范。良好的代码规范可以提高代码质量,减少错误,并使团队协作更加顺畅。

ESLint 配置

ESLint 用于检查代码质量和编码风格。

1. 基础配置

项目使用 @antfu/eslint-config 作为基础配置:

// eslint.config.js
import antfu from "@antfu/eslint-config"
 
export default antfu(
  {
    markdown: false,
    formatters: {
      css: true,
      html: true,
      markdown: "prettier",
    },
    typescript: {
      overrides: {
        "node/prefer-global/process": ["off"],
        "import/order": [
          "warn",
          {
            "newlines-between": "always",
          },
        ],
      },
    },
  },
  {
    rules: {
      "import/order": "warn",
      "sort-imports": "off",
      "perfectionist/sort-imports": "off",
      "perfectionist/sort-named-imports": "off",
      "perfectionist/sort-exports": "off",
      "style/quotes": ["error", "double"],
    },
  },
)

2. 自定义规则

.eslintrc.json 中可以添加自定义规则:

{
  "extends": "@antfu",
  "rules": {
    // 强制使用单引号
    "quotes": ["error", "single"],
    // 语句末尾必须使用分号
    "semi": ["error", "always"],
    // 缩进使用 2 个空格
    "indent": ["error", 2],
    // 强制使用 === 和 !==
    "eqeqeq": ["error", "always"],
    // 禁止未使用的变量
    "no-unused-vars": "error"
  }
}

3. 忽略文件

创建 .eslintignore 文件来忽略特定文件:

dist
.nuxt
node_modules
*.min.js

Git Hooks

项目使用 simple-git-hookslint-staged 在提交代码时进行检查。

1. simple-git-hooks 配置

package.json 中配置:

{
  "simple-git-hooks": {
    "pre-commit": "pnpm lint-staged && pnpm type-check",
    "commit-msg": "pnpm commitlint --edit ${1}"
  },
  "lint-staged": {
    "*.{js,ts,vue}": [
      "eslint --fix"
    ]
  }
}

2. 脚本命令

package.json 中的脚本命令:

{
  "scripts": {
    "format": "eslint . --fix",
    "lint": "eslint .",
    "lint:fix": "eslint . --fix",
    "type-check": "nuxi typecheck"
  }
}

提交规范

项目使用 commitlint 规范提交信息。

1. 提交格式

type(scope): subject

2. 类型说明

  • feat: 新功能
  • fix: 修复问题
  • docs: 文档修改
  • style: 代码格式修改
  • refactor: 代码重构
  • perf: 性能优化
  • test: 测试相关
  • chore: 构建过程或辅助工具的变动

3. 示例

feat(auth): 添加用户登录功能
fix(components): 修复按钮点击事件失效问题
docs(readme): 更新安装说明
style(lint): 统一代码缩进风格

使用方法

1. 代码检查

# 检查所有文件
pnpm lint
 
# 自动修复
pnpm lint:fix
 
# 格式化代码
pnpm format

2. VS Code 集成

settings.json 中添加:

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}

常见问题

下一步

目录