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

Next.js+TypeScript项目Eslint未使用变量错误排查求助

问题:Next.js + TypeScript项目中ESLint误报未使用变量

我正在开发一个基于Next.js + TypeScript的项目,采用Auth0做身份认证。我确认所有useState声明的变量都已在代码中使用,但每次运行ESLint都会失败,怀疑是配置问题。以下是相关内容:

精简后的Login组件代码

'use client';
import Image from 'next/image';
import { useState } from 'react';
import SignupForm from './SignupForm';
import { FormsToggleProps } from './Types';

const Login = ({ showLogin, setShowLogin }: FormsToggleProps) => {

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password }),
      });

      if (res.ok) {
        console.log('Login successful');
        // Handle successful login
      } else {
        const data = await res.json();
        setError(data.message || 'Login failed');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Something went wrong');
    }
  };

  return (
    <section className="bg-gray-50 dark:bg-gray-900">
        <div className="w-full rounded-lg bg-white shadow sm:max-w-md md:mt-0 xl:p-0 dark:border dark:border-gray-700 dark:bg-gray-800">
          <div className="space-y-4 p-6 sm:p-8 md:space-y-6">
            {showLogin ? (
              <>
                <h1 className="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white">
                  Sign in to your account
                </h1>
                <form className="space-y-4 md:space-y-6" onSubmit={handleSubmit}>
                  <div>
                    <label
                      htmlFor="email"
                      className="mb-2 block text-sm font-medium text-gray-900 dark:text-white"
                    >
                      Your email
                    </label>
                    <input
                      type="email"
                      name="email"
                      id="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      required
                    />
                  </div>
                  <div>
                    <label
                      htmlFor="password"
                      className="mb-2 block text-sm font-medium text-gray-900 dark:text-white"
                    >
                      Password
                    </label>
                    <input
                      type="password"
                      name="password"
                      id="password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      required
                    />
                  </div>
                  {error && <p className="text-red-500">{error}</p>}
                  <button
                    type="submit"
                    className="focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800 w-full rounded-lg bg-blue-600 px-5 py-2.5 text-center text-sm font-medium text-white hover:bg-blue-800 focus:outline-none focus:ring-4">
                  Sign in
                  </button>
                </form>
              </>
            ) : (
              <SignupForm />
            )}
          </div>
        </div>
    </section>
  );
};

export default Login;

注:补全了原代码中未闭合的button标签和return部分的结构,确保语法完整。

.eslintrc.json配置

//.eslintrc.json
{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:@next/next/recommended",
    "plugin:prettier/recommended"
  ],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  
  "rules": {
    "prettier/prettier": ["error", { "endOfLine": "auto" }],
    "react/react-in-jsx-scope": "off"
  }
}

ESLint错误信息

$ git commit -m 'update Login'
✔ Backed up original state in git stash (63a4bd8)
✔ Hiding unstaged changes to partially staged files...
⚠ Running tasks for staged files...
  ❯ package.json — 1 file
    ❯ *.{js,jsx,ts,tsx} — 1 file
      ✖ eslint --fix [FAILED]
      ◼ prettier --write
↓ Skipped because of errors from tasks.
↓ Skipped because of errors from tasks.
✔ Reverting to original state because of errors...
✔ Cleaning up temporary files...

✖ eslint --fix:
8:17  error  'setEmail' is assigned a value but never used     @typescript-eslint/no-unused-vars
   9:20  error  'setPassword' is assigned a value but never used  @typescript-eslint/no-unused-vars
  10:10  error  'error' is assigned a value but never used        @typescript-eslint/no-unused-vars
  31:14  error  'error' is defined but never used                 @typescript-eslint/no-unused-vars

✖ 4 problems (4 errors, 0 warnings)

husky - pre-commit script failed (code 1)

解决方案

1. 修正ESLint配置,添加TypeScript支持

当前配置缺少TypeScript ESLint插件的核心配置,导致ESLint无法正确识别TypeScript+JSX中的变量使用场景。修改.eslintrc.json如下:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:@next/next/recommended",
    "plugin:prettier/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint"],
  "rules": {
    "prettier/prettier": ["error", { "endOfLine": "auto" }],
    "react/react-in-jsx-scope": "off"
  }
}

关键修改点:

  • 添加parser: "@typescript-eslint/parser"指定TS解析器
  • 在extends中加入plugin:@typescript-eslint/recommended
  • 添加plugins: ["@typescript-eslint"]启用TS插件
  • 将ecmaVersion改为latest以支持最新语法

2. 安装必要依赖

确保项目已安装TypeScript ESLint相关依赖:

npm install --save-dev @typescript-eslint/eslint-plugin @typescript-eslint/parser

3. 确认代码语法完整性

原代码存在未闭合的button标签和不完整的return结构,这会导致ESLint解析异常,需补全代码(如前面精简代码所示)。

内容的提问来源于stack exchange,提问作者M-Sev1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:55:54