非create-react-app项目配置eslintrc集成React(Airbnb+TS)方法
非create-react-app项目ESLint配置React箭头函数组件方案
报错原因
react/function-component-definition 规则由eslint-plugin-react提供,引入的Airbnb规则集默认要求React函数组件必须使用function关键字声明,和期望统一使用箭头函数的规范冲突,直接覆写对应规则即可。
前置依赖确认
非CRA脚手架搭建的项目,先确保相关ESLint插件已安装,执行以下命令安装缺失依赖:
npm install eslint-plugin-react eslint-plugin-react-hooks @typescript-eslint/parser --save-dev
配置修改步骤
- 调整
extends顺序与冗余项
当前配置里的plugin:react/recommended已经被Airbnb规则集内置,重复声明不生效可以删除;注意plugin:prettier/recommended必须放在extends数组最后一位,才能正确覆盖其他规则集的格式冲突项。 - 新增规则覆写配置
在rules字段中添加对应规则,强制所有组件使用箭头函数定义:rules: { // 其他原有自定义规则保持不变 'react/function-component-definition': [ 'error', { namedComponents: 'arrow-function', // 命名组件使用箭头函数 unnamedComponents: 'arrow-function', // 匿名组件使用箭头函数 }, ], // React 17+ 支持JSX自动转换,不需要手动引入React时可以开启以下规则避免误报 'react/react-in-jsx-scope': 'off', } - 补充React版本自动检测配置
在配置文件根节点添加settings字段,避免规则和实际使用的React版本不匹配:settings: { react: { version: 'detect', }, }, - 补全TypeScript解析配置
airbnb-typescript要求必须在parserOptions中指定项目tsconfig.json路径,否则会抛出解析错误,确保配置里有对应字段:parserOptions: { ecmaVersion: 'latest', sourceType: 'module', ecmaFeatures: { jsx: true, }, project: './tsconfig.json', // 替换为项目实际的tsconfig路径 }
完整配置参考
module.exports = { parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 'latest', sourceType: 'module', ecmaFeatures: { jsx: true, }, project: './tsconfig.json', }, extends: [ 'airbnb', 'airbnb-typescript', 'airbnb/hooks', 'plugin:jest/recommended', 'plugin:prettier/recommended', ], settings: { react: { version: 'detect', }, }, rules: { 'react/function-component-definition': [ 'error', { namedComponents: 'arrow-function', unnamedComponents: 'arrow-function', }, ], 'react/react-in-jsx-scope': 'off', }, };
配置完成后重启ESLint服务,所有使用普通function声明的组件会被标记为错误,箭头函数定义的组件可正常通过校验,实现统一编码规范。
内容的提问来源于stack exchange,提问作者meez
相关产品推荐
相关产品推荐

