将.eslintrc迁移至eslint.config.mjs时出现类型错误求助
将.eslintrc迁移至eslint.config.mjs时出现类型错误求助
嗨,我看你在从旧的.eslintrc迁移到新的扁平配置eslint.config.mjs时碰到了那个类型错误,别慌,这个问题其实是新配置格式的规则没摸透~
先给你点明错误原因:ESLint的扁平配置(也就是eslint.config.mjs这种格式)要求导出的数组里的每一项都必须是配置对象,而你现在数组第一个元素直接写了字符串'eslint:recommended',这不符合新规则,所以才会抛出"Unexpected non-object config"这个错误。
接下来给你修正后的完整配置,我帮你把所有问题都理顺了:
// eslint.config.mjs import globals from 'globals' import eslint from '@eslint/js' import eslintPluginReact from 'eslint-plugin-react' import typescriptEslint from '@typescript-eslint/eslint-plugin' import importPlugin from 'eslint-plugin-import' import tsParser from '@typescript-eslint/parser' const filesList = ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'] export default [ // 用官方导出的配置对象代替字符串,符合扁平配置要求 eslint.configs.recommended, // TypeScript ESLint的推荐配置本身就是对象格式,直接用就行 typescriptEslint.configs.recommended, { files: filesList, languageOptions: { ecmaVersion: 2022, sourceType: 'module', globals: { ...globals.browser, ...globals.node }, // 解析器要通过导入的方式指定,不能直接写字符串 parser: tsParser }, // 必须显式注册用到的插件 plugins: { react: eslintPluginReact, '@typescript-eslint': typescriptEslint, import: importPlugin }, extends: [ 'plugin:react/recommended', 'plugin:@typescript-eslint/eslint-recommended', 'plugin:import/errors', 'plugin:import/warnings' ], settings: { 'import/resolver': { node: { extensions: ['.js', '.jsx', '.ts', '.tsx'] }, alias: { map: [ ['@renderer', './src/renderer'], ['@components', './src/renderer/components'], ['@common', './src/common'], ['@main', './src/main'], ['@src', './src'], ['@misc', './misc'], ['@assets', './assets'] ], extensions: ['.js', '.jsx', '.ts', '.tsx'] } }, react: { version: 'detect' } }, rules: { 'react/prop-types': 'off', '@typescript-eslint/no-var-requires': 'off' } } ]
再给你划几个重点:
- 旧配置里的
"extends"字符串,在扁平配置里要么像eslint.configs.recommended这样导入官方预设对象直接放在顶层数组,要么在配置对象的extends里继续用字符串(但前提是插件已经在plugins里注册好了)。 - 所有顶层数组的元素必须是配置对象,绝对不能直接放字符串!
- 要额外安装
@eslint/js这个依赖(如果还没装的话),执行npm install @eslint/js --save-dev就行,因为新格式需要从这里导入官方的推荐配置。 - 解析器
@typescript-eslint/parser要单独导入,然后在languageOptions.parser里指定,不能像旧配置那样直接写字符串。
这样修改后,那个类型错误应该就消失了,你可以试试运行ESLint看看效果~
备注:内容来源于stack exchange,提问作者Ziv Barber
相关产品推荐
相关产品推荐

