Skip to content

Eslint 配置

Eslint 解决问题

它能在我们编写代码的时候就检测出程序可能出现的隐藏BUG,帮助我们及时发现并修复问题。

Eslint 配置文件

  • 安装完react项目后 他根目录下面就有一个eslint.config.js文件
js
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
import { defineConfig, globalIgnores } from "eslint/config";

export default defineConfig([
  globalIgnores(["dist"]),
  {
    files: ["**/*.{ts,tsx}"],
    extends: [
      js.configs.recommended,
      tseslint.configs.recommended,
      reactHooks.configs.flat.recommended,
      reactRefresh.configs.vite,
    ],
    languageOptions: {
      globals: globals.browser,
    },
  },
]);

我要是想增加自己的特殊规则

  • 新增加rules 规则
js
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
import { defineConfig, globalIgnores } from "eslint/config";

export default defineConfig([
  globalIgnores(["dist"]),
  {
    files: ["**/*.{ts,tsx}"],
    extends: [
      js.configs.recommended,
      tseslint.configs.recommended,
      reactHooks.configs.flat.recommended,
      reactRefresh.configs.vite,
    ],
    languageOptions: {
      globals: globals.browser,
    },
    // ↓↓↓ 在这里加你的自定义规则 ↓↓↓
    // rules: {
    //   // 禁用 console(生产环境常用)
    //   'no-console': 'warn',

    //   // 强制使用 === 而不是 ==
    //   'eqeqeq': 'error',

    //   // 禁止未使用的变量(覆盖 TS 推荐的 warn,改为 error)
    //   '@typescript-eslint/no-unused-vars': ['error', {
    //     argsIgnorePattern: '^_',      // 以 _ 开头的参数不报
    //     varsIgnorePattern: '^_',
    //   }],

    //   // 禁止 any 类型
    //   '@typescript-eslint/no-explicit-any': 'warn',

    //   // 强制函数返回类型声明
    //   '@typescript-eslint/explicit-function-return-type': 'off',
    // },
  },
]);