ESLint配置报错:.eslintrc.js存在未识别的顶级属性files
解决ESLint配置中"Unexpected top-level property 'files'"错误
错误原因
你使用的.eslintrc.js是ESLint的旧版配置格式,顶层files属性仅支持在ESLint 8.21+推出的扁平配置文件(即eslint.config.js)中使用,旧格式无法识别该字段,因此触发报错。
两种解决办法
办法一:改用扁平配置文件(推荐)
将.eslintrc.js重命名为eslint.config.js,调整配置结构为数组包裹的对象形式,把files放在配置对象内部:
module.exports = [ { // 指定要检查的文件类型 files: ['*.ts', '*.jsx', '*.tsx'], extends: [ 'react-app', 'react-app/jest', 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier', ], parser: '@typescript-eslint/parser', parserOptions: { project: './tsconfig.json', ecmaFeatures: { jsx: true, }, ecmaVersion: 'latest', sourceType: 'module', }, rules: { 'testing-library/no-node-access': 'off', }, } ];
办法二:保留旧格式配置文件
直接删除.eslintrc.js中的files字段,改用命令行参数或其他方式指定检查文件:
- 修改后的
.eslintrc.js:
module.exports = { extends: [ 'react-app', 'react-app/jest', 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier', ], parser: '@typescript-eslint/parser', parserOptions: { project: './tsconfig.json', ecmaFeatures: { jsx: true, }, ecmaVersion: 'latest', sourceType: 'module', }, rules: { 'testing-library/no-node-access': 'off', }, };
- 修正precommit钩子的命令:你当前的命令存在语法错误,多余的
'*.ts', '*.tsx'需要删除,正确命令应为:
BABEL_ENV=development eslint src --ext .js,.jsx,.ts,.tsx --fix
该命令已通过--ext指定了要检查的文件扩展名,完全可以替代配置里files的作用。
如果需要排除某些文件,可在.eslintrc.js中添加ignorePatterns字段,示例:
ignorePatterns: ['dist/**', '*.config.js']
内容的提问来源于stack exchange,提问作者Kevin Ham
相关产品推荐
相关产品推荐

