如何配置ESLint指定待检查文件?React Native项目适配方案
解决方法
1. 修正ESLint配置:替换无效的includePaths
ESLint并没有includePaths这个配置项,你需要用files或ignorePatterns来指定要检查的文件范围。修改你的.eslintrc.js:
module.exports = { env: { browser: true, es2021: true, 'react-native/react-native': true, }, extends: [ 'plugin:react/recommended', 'standard-with-typescript', 'plugin:react-native-a11y/android' ], overrides: [], parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 'latest', sourceType: 'module', project: './tsconfig.json' }, plugins: ['react', 'react-native'], rules: { indent: ['error', 2], 'linebreak-style': ['error', 'unix'], semi: ['error', 'always'] }, // 指定要检查的文件,覆盖默认的src目录规则 files: ['./components/**/*.{ts,tsx}', './screens/**/*.{ts,tsx}', './**/*.{ts,tsx}'], // 排除不需要检查的目录/文件 ignorePatterns: ['node_modules/', 'dist/'] };
如果想更宽泛地检查所有ts/tsx文件,也可以简化成:
files: ['**/*.{ts,tsx}'], ignorePatterns: ['node_modules/']
2. 同步tsconfig.json的文件范围
因为你使用了@typescript-eslint/parser并指定了project: './tsconfig.json',TypeScript的配置必须包含你要检查的文件,否则ESLint会报错。修改tsconfig.json的include字段:
{ "compilerOptions": { // 你的原有配置 }, "include": [ "components/**/*", "screens/**/*", "*.{ts,tsx}" // 根目录的ts/tsx文件 ], "exclude": ["node_modules"] }
3. 简化package.json的lint命令
现在你可以直接运行eslint命令,无需额外传路径,把package.json里的lint命令改成:
"lint": "eslint ."
4. 确保编辑器实时检测生效
以VS Code为例,检查以下设置:
- 安装并启用ESLint插件
- 在VS Code的设置(settings.json)中,确保没有强制指定ESLint的检查路径:
"eslint.options": {}, // 不要在这里指定paths,让插件读取配置文件 "eslint.validate": ["typescript", "typescriptreact"] - 重启VS Code的ESLint服务(打开命令面板:
Ctrl+Shift+P,输入ESLint: Restart ESLint Server)
这样不管是运行npm run lint还是编辑器实时检测,都会自动检查你指定的components、screens等目录下的文件了。
内容的提问来源于stack exchange,提问作者Stretch0
相关产品推荐
相关产品推荐

