Ionic 7 React TypeScript默认ESLint设置导致VSCode不显示useEffect缺失依赖警告
解决Ionic 7 React TypeScript项目ESLint不提示useEffect依赖缺失的问题
Ionic 6及更早版本的项目依赖react-app ESLint配置集,其中已经内置了react-hooks相关规则;但Ionic 7默认使用的plugin:react/recommended和eslint:recommended不包含这些规则,所以需要手动补充配置:
- 安装
eslint-plugin-react-hooks插件
在项目根目录执行命令:
npm install eslint-plugin-react-hooks --save-dev
如果使用yarn:
yarn add eslint-plugin-react-hooks --dev
- 修改
.eslintrc.js配置文件
更新配置,添加react-hooks插件并启用核心规则:
module.exports = { root: true, env: { browser: true, es2021: true, node: true, }, extends: [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:@typescript-eslint/recommended', ], parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 'latest', sourceType: 'module', }, plugins: [ 'react', '@typescript-eslint', 'react-hooks' // 新增react-hooks插件 ], rules: { // 启用React Hooks规则 'react-hooks/rules-of-hooks': 'error', // 检测Hooks使用规范 'react-hooks/exhaustive-deps': 'warn', // 提示缺失的依赖项(设为warn和Ionic6行为一致) // 可选:关闭React17+不需要的规则 'react/react-in-jsx-scope': 'off', '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }] }, settings: { react: { version: 'detect' // 自动识别React版本 } } };
重启VSCode的ESLint服务
打开VSCode命令面板(快捷键:Ctrl+Shift+P / Cmd+Shift+P),输入并执行ESLint: Restart ESLint Server。验证效果
编写一段包含缺失依赖的useEffect代码,比如:
import { useEffect, useState } from 'react'; const TestComponent = () => { const [count, setCount] = useState(0); useEffect(() => { document.title = `Count: ${count}`; }, []); // 此处未添加count作为依赖 return <button onClick={() => setCount(count + 1)}>Click</button>; }; export default TestComponent;
此时应该能看到ESLint警告,提示缺失count依赖,且可使用自动修复功能补全依赖数组。
内容的提问来源于stack exchange,提问作者DevMike
相关产品推荐
相关产品推荐

