You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript项目中使用新版ESLint配置文件语法

React TypeScript项目ESLint新版Flat Config配置方案

直接给你适配好的eslint.config.mjs配置文件,完全匹配你的需求:

import js from '@eslint/js';
import typescriptEslint from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
import reactPlugin from 'eslint-plugin-react';
import reactHooks from 'eslint-plugin-react-hooks';
import { LegacyConfig } from '@eslint/eslintrc';
// 导入UI团队的ESLint配置
import uiEslintConfig from '@ui/eslint-config';

// 将旧格式的@ui配置转换为新版Flat Config格式
const convertedUiConfig = new LegacyConfig(uiEslintConfig).toFlatConfig();

export default [
  // 基础JS推荐规则
  js.configs.recommended,
  // 导入转换后的UI团队配置
  ...convertedUiConfig,
  // TypeScript + React核心检查规则
  {
    files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
    languageOptions: {
      parser: tsParser,
      parserOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module',
        ecmaFeatures: {
          jsx: true
        },
        project: './tsconfig.json' // 确保路径和你的项目根目录tsconfig一致
      }
    },
    plugins: {
      '@typescript-eslint': typescriptEslint,
      react: reactPlugin,
      'react-hooks': reactHooks
    },
    rules: {
      // 继承TS和React的推荐规则(若UI配置未覆盖)
      ...typescriptEslint.configs.recommended.rules,
      ...reactPlugin.configs.recommended.rules,
      ...reactHooks.configs.recommended.rules,
      // 适配React 17+的规则调整
      'react/react-in-jsx-scope': 'off',
      'react/jsx-uses-react': 'off',
      // 自定义规则示例:允许下划线开头的未使用参数
      '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }]
    }
  },
  // 忽略无需检查的文件/目录
  {
    ignores: ['node_modules/', 'dist/', 'build/', '*.config.*']
  }
];

关键细节说明

  1. 旧配置转换:如果@ui/eslint-config还是传统的eslintrc格式,必须用@eslint/eslintrc的LegacyConfig转换为Flat Config才能正常导入;若你的UI配置已经是新版Flat格式,直接把...convertedUiConfig替换为...uiEslintConfig即可。
  2. 文件范围:通过files字段明确指定要检查的文件类型,覆盖TS、TSX、JS、JSX所有需要检查的文件。
  3. 解析器配置:tsParser必须配合project字段启用类型检查相关规则,路径要和项目根目录的tsconfig.json对应。
  4. 插件注册:新版Flat Config需要手动导入并注册所有用到的插件,不像旧版extends会自动加载依赖插件。

必要依赖安装

确保你的项目已安装这些依赖包:

npm install eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-react eslint-plugin-react-hooks @eslint/js @eslint/eslintrc --save-dev

验证配置有效性

运行以下命令测试配置是否正常工作:

npx eslint . --ext .ts,.tsx,.js,.jsx

内容的提问来源于stack exchange,提问作者danchez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:33:37