当前位置:首页 > React

react项目如何添加eslint

2026-03-10 22:58:44React

安装 ESLint 及相关依赖

在项目根目录下运行以下命令安装 ESLint 及相关插件:

npm install eslint eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

初始化 ESLint 配置

运行以下命令生成 ESLint 配置文件:

npx eslint --init

根据提示选择 React 和 TypeScript(如适用)相关配置选项。

配置 .eslintrc.js

生成的配置文件示例(可根据需求调整):

react项目如何添加eslint

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'plugin:jsx-a11y/recommended',
  ],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['react', 'react-hooks', 'jsx-a11y'],
  rules: {
    'react/prop-types': 'off',
    'react/react-in-jsx-scope': 'off',
  },
};

添加 TypeScript 支持(可选)

若项目使用 TypeScript,需修改配置:

module.exports = {
  extends: [
    // ...其他配置
    'plugin:@typescript-eslint/recommended',
  ],
  parser: '@typescript-eslint/parser',
  plugins: [
    // ...其他插件
    '@typescript-eslint',
  ],
};

创建忽略文件 .eslintignore

添加需要忽略检查的文件或目录:

react项目如何添加eslint

node_modules
build
dist
*.config.js

添加 npm 脚本

package.json 中添加 lint 命令:

"scripts": {
  "lint": "eslint .",
  "lint:fix": "eslint . --fix"
}

配置编辑器集成

在 VSCode 中安装 ESLint 扩展,并确保工作区设置启用自动修复:

{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}

自定义规则配置

根据项目需求调整规则,常见规则示例:

rules: {
  'jsx-a11y/anchor-is-valid': ['warn', { aspects: ['invalidHref'] }],
  'react-hooks/rules-of-hooks': 'error',
  'react-hooks/exhaustive-deps': 'warn',
  'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'warn'
}

标签: 项目react
分享给朋友:

相关文章

react native 如何

react native 如何

React Native 开发基础 React Native 是一个用于构建跨平台移动应用的框架,允许开发者使用 JavaScript 和 React 编写代码,同时生成原生 iOS 和 Androi…

如何开发react

如何开发react

开发React应用的基本步骤 安装Node.js和npm 确保系统中已安装Node.js(包含npm)。可通过官网下载安装包,安装后验证版本: node -v npm -v 创建React项目…

如何用react

如何用react

使用React的基本步骤 安装Node.js和npm 确保系统已安装Node.js和npm。Node.js自带npm,可从官网下载安装包。安装完成后,通过命令行验证版本: node -v npm -…

uniapp项目案例

uniapp项目案例

uniapp项目案例概述 uniapp作为跨平台开发框架,广泛应用于多端应用开发(H5、小程序、App等)。以下是一些典型项目案例及实现方法,涵盖电商、社交、工具等场景。 电商类案例 案…

vue实现项目

vue实现项目

Vue 项目实现指南 环境准备 确保已安装 Node.js(建议版本 16+)和 npm/yarn。通过以下命令安装 Vue CLI: npm install -g @vue/cli 创建项目 使用…

vue项目如何实现

vue项目如何实现

安装Vue.js 通过npm或yarn安装Vue.js。确保Node.js环境已配置完成。 npm install vue # 或 yarn add vue 创建Vue项目 使用Vue CLI工具快…