下面,我们来系统的梳理关于 ESLint + Prettier:React 代码规范与自动化 的基本知识点:


一、代码规范工具概述

1.1 为什么需要代码规范?

  • 一致性:统一团队编码风格
  • 可读性:提高代码可维护性
  • 质量保证:提前发现潜在错误
  • 自动化:减少代码审查负担
  • 协作效率:标准化开发流程

1.2 ESLint vs Prettier

特性 ESLint Prettier
主要功能 代码质量检查 代码格式化
检查类型 语法错误、代码风格、最佳实践 代码格式、缩进、引号等
可配置性 高度可配置 有限配置
自动修复 支持部分规则自动修复 完全自动格式化
扩展性 支持插件和自定义规则 固定格式化规则

1.3 工具协同工作流程

编写代码
ESLint 检查
是否有错误?
修复问题
Prettier 格式化
提交代码

二、ESLint 深度解析

2.1 安装与配置

# 基本安装
npm install --save-dev eslint

# React 项目推荐安装
npm install --save-dev eslint eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y @typescript-eslint/parser @typescript-eslint/eslint-plugin

# Create React App 已经内置 ESLint

2.2 配置文件格式

.eslintrc.js (推荐)

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'plugin:jsx-a11y/recommended',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: [
    'react',
    'react-hooks',
    'jsx-a11y',
    '@typescript-eslint',
  ],
  rules: {
    // 自定义规则
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
};

2.3 核心配置详解

环境配置 (env)
env: {
  browser: true,    // 浏览器环境全局变量
  node: true,       // Node.js 环境全局变量
  es6: true,        // ES6+ 语法支持
  jest: true,       // Jest 测试框架
}
扩展配置 (extends)
extends: [
  'eslint:recommended',                    // ESLint 推荐规则
  'plugin:react/recommended',             // React 推荐规则
  'plugin:react-hooks/recommended',       // React Hooks 规则
  'plugin:@typescript-eslint/recommended', // TypeScript 规则
  'prettier',                             // 禁用与 Prettier 冲突的规则
  'prettier/react',                       // 禁用 React 相关冲突规则
  'prettier/@typescript-eslint',          // 禁用 TypeScript 相关冲突规则
]
规则配置 (rules)
rules: {
  // 错误级别:'off', 'warn', 'error'
  'react/prop-types': 'off', // 关闭 prop-types 检查(TypeScript 项目中)
  'react-hooks/exhaustive-deps': 'warn', // 检查 effect 依赖
  'no-console': 'warn', // 警告 console 语句
  'no-unused-vars': 'error', // 错误:未使用变量
  'prefer-const': 'error', // 优先使用 const
  
  // 带有选项的规则
  'complexity': ['error', { max: 10 }], // 圈复杂度限制
  'max-depth': ['error', 4], // 最大嵌套深度
}

2.4 常用 React 相关规则

rules: {
  // React 特定规则
  'react/jsx-uses-react': 'error',
  'react/jsx-uses-vars': 'error',
  'react/jsx-no-undef': 'error',
  'react/jsx-no-duplicate-props': 'error',
  'react/jsx-key': 'error',
  
  // Hooks 规则
  'react-hooks/rules-of-hooks': 'error',
  'react-hooks/exhaustive-deps': 'warn',
  
  // 可访问性规则
  'jsx-a11y/alt-text': 'error',
  'jsx-a11y/anchor-is-valid': 'error',
}

三、Prettier 深度解析

3.1 安装与配置

npm install --save-dev prettier eslint-config-prettier eslint-plugin-prettier

3.2 配置文件

.prettierrc (推荐)

{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "bracketSpacing": true,
  "jsxBracketSameLine": false,
  "arrowParens": "avoid",
  "endOfLine": "lf"
}

3.3 配置选项详解

选项 默认值 描述 推荐设置
printWidth 80 行宽限制 80-100
tabWidth 2 缩进空格数 2
useTabs false 使用制表符 false
semi true 分号 true
singleQuote false 单引号 true
trailingComma “none” 尾随逗号 “es5”
bracketSpacing true 对象括号空格 true
jsxBracketSameLine false JSX 括号同行 false
arrowParens “avoid” 箭头函数参数括号 “avoid”
endOfLine “lf” 行尾符 “lf”

3.4 忽略文件配置

.prettierignore

# 忽略目录
node_modules/
dist/
build/
coverage/

# 忽略文件
package-lock.json
yarn.lock

# 忽略特定文件类型
*.min.js
*.bundle.js

四、ESLint + Prettier 集成

4.1 完整集成配置

// .eslintrc.js
module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier', // 必须放在最后
    'prettier/react',
    'prettier/@typescript-eslint',
  ],
  plugins: ['prettier'],
  rules: {
    'prettier/prettier': 'error', // 将 Prettier 规则作为 ESLint 错误
  },
};

4.2 解决规则冲突

// 在 .eslintrc.js 中禁用冲突规则
rules: {
  // 禁用与 Prettier 冲突的 ESLint 规则
  'indent': 'off',
  'quotes': 'off',
  'semi': 'off',
  'comma-dangle': 'off',
  'max-len': 'off',
  
  // 启用 Prettier 规则
  'prettier/prettier': 'error',
}

五、编辑器集成与自动化

5.1 VS Code 配置

// .vscode/settings.json
{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ],
  "prettier.requireConfig": true,
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

5.2 推荐 VS Code 扩展

  • ESLint:ESLint 集成
  • Prettier - Code formatter:Prettier 格式化
  • Error Lens:实时显示错误
  • Bracket Pair Colorizer:括号颜色匹配

5.3 Git Hooks 自动化

# 安装 Husky 和 lint-staged
npm install --save-dev husky lint-staged

package.json 配置

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "pre-push": "npm run test"
    }
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ],
    "*.{json,md,html,css,scss}": [
      "prettier --write"
    ]
  }
}

六、React 特定配置

6.1 TypeScript + React 配置

// .eslintrc.js
module.exports = {
  parser: '@typescript-eslint/parser',
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:react/recommended',
    'prettier/@typescript-eslint',
    'prettier/react',
  ],
  rules: {
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-explicit-any': 'warn',
    'react/prop-types': 'off', // TypeScript 中不需要 prop-types
  },
};

6.2 Hooks 最佳实践规则

rules: {
  'react-hooks/rules-of-hooks': 'error',
  'react-hooks/exhaustive-deps': [
    'warn',
    {
      'additionalHooks': '(useMemoized|useCustomHook)'
    }
  ],
}

6.3 组件命名规范

rules: {
  'react/display-name': 'error',
  'react/jsx-pascal-case': 'error',
  'react/jsx-no-bind': [
    'warn',
    {
      'ignoreDOMComponents': true,
      'ignoreRefs': true,
      'allowArrowFunctions': true,
      'allowFunctions': false,
      'allowBind': false
    }
  ],
}

七、自定义规则开发

7.1 创建自定义 ESLint 规则

// eslint-plugin-custom-rules.js
module.exports = {
  rules: {
    'no-console-in-production': {
      create: function(context) {
        return {
          CallExpression(node) {
            if (node.callee.object?.name === 'console' && 
                process.env.NODE_ENV === 'production') {
              context.report({
                node,
                message: 'Console statements are not allowed in production'
              });
            }
          }
        };
      }
    }
  }
};

7.2 使用自定义规则

// .eslintrc.js
module.exports = {
  plugins: ['custom-rules'],
  rules: {
    'custom-rules/no-console-in-production': 'error'
  }
};

八、团队协作配置

8.1 共享配置方案

方案1:npm 包共享

# 创建配置包
npm init @eslint/config

# 发布配置包
npm publish

方案2:Git 子模块

git submodule add https://github.com/your-team/eslint-config.git

8.2 多项目统一配置

// eslint-config-your-team/index.js
module.exports = {
  extends: [
    require.resolve('./rules/base'),
    require.resolve('./rules/react'),
    require.resolve('./rules/typescript'),
    require.resolve('./rules/prettier'),
  ],
};

九、性能优化与问题解决

9.1 性能优化配置

// .eslintrc.js
module.exports = {
  // 忽略大量文件
  ignorePatterns: ['dist/', 'build/', 'coverage/'],
  
  // 缓存配置
  cache: true,
  cacheLocation: './node_modules/.cache/eslint/',
  
  // 仅检查必要文件
  overrides: [
    {
      files: ['src/**/*.{js,jsx,ts,tsx}'],
      excludedFiles: ['**/*.test.{js,jsx,ts,tsx}'],
    }
  ]
};

9.2 常见问题解决

问题1:ESLint 和 Prettier 冲突
// 安装 eslint-config-prettier
npm install --save-dev eslint-config-prettier

// 确保在 extends 数组中最后引入
extends: [
  'other-configs',
  'prettier' // 必须放在最后
]
问题2:TypeScript 解析错误
// 确保 parser 配置正确
parser: '@typescript-eslint/parser',
parserOptions: {
  project: './tsconfig.json',
  sourceType: 'module',
}
问题3:Husky 钩子不执行
# 重新安装 Husky
npm uninstall husky
npm install --save-dev husky

# 启用 Git hooks
npx husky install

十、完整示例配置

10.1 React + TypeScript 完整配置

.eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:jsx-a11y/recommended',
    'prettier',
    'prettier/react',
    'prettier/@typescript-eslint',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
    project: './tsconfig.json',
  },
  plugins: [
    'react',
    'react-hooks',
    '@typescript-eslint',
    'jsx-a11y',
    'prettier',
  ],
  rules: {
    'prettier/prettier': 'error',
    'react/prop-types': 'off',
    'react/react-in-jsx-scope': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
};

.prettierrc

{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "bracketSpacing": true,
  "jsxBracketSameLine": false,
  "arrowParens": "avoid",
  "endOfLine": "lf"
}

package.json 脚本

{
  "scripts": {
    "lint": "eslint src --ext .js,.jsx,.ts,.tsx",
    "lint:fix": "eslint src --ext .js,.jsx,.ts,.tsx --fix",
    "format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"",
    "lint:ci": "eslint src --ext .js,.jsx,.ts,.tsx --max-warnings=0"
  }
}

十一、总结

关键最佳实践

  1. 统一配置:团队使用相同的规则配置
  2. 自动化:通过 Git Hooks 自动检查和格式化
  3. 渐进采用:逐步引入规则,避免一次性太多限制
  4. 定期审查:定期更新规则以适应新技术

工具选择建议

graph TD
A[项目类型] --> B{选择方案}
B -->|Create React App| C[使用内置 ESLint]
B -->|自定义配置| D[手动配置 ESLint + Prettier]
B -->|TypeScript 项目| E[添加 @typescript-eslint]
C --> F[按需扩展规则]
D --> G[完整自定义配置]
E --> H[类型感知规则]
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐