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

如何在eslint.config.mjs中启用TypeScript的ESLint代码检查

解决ESLint无法检测TypeScript文件的问题

问题描述

为Node项目配置ESLint后,执行npx eslint .仅能检测出index.js的代码错误,但存在明显问题的app.ts文件完全未被ESLint识别(比如未声明类型的函数参数、混合import/require语法、未使用变量等问题都没有触发报错)。

解决步骤

1. 确保安装必要依赖

首先确认已安装TypeScript及ESLint的TS相关插件,若未安装执行以下命令:

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

2. 修正ESLint配置文件

原eslint.config.mjs的TypeScript配置存在解析器选项缺失、配置结构不合理的问题,替换为以下内容:

import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";

/** @type {import('eslint').Linter.Config[]} */
export default [
  // 全局基础配置(Node项目使用node环境变量而非browser)
  { languageOptions: { globals: globals.node } },

  // JavaScript文件专属配置
  {
    files: ["**/*.js"],
    languageOptions: { sourceType: "commonjs" },
    ...pluginJs.configs.recommended,
  },

  // TypeScript文件专属配置
  ...tseslint.configs.recommended.map(config => ({
    ...config,
    files: ["**/*.ts"],
    languageOptions: {
      ...config.languageOptions,
      sourceType: "module",
      parserOptions: {
        project: "./tsconfig.json", // 指定TS配置文件路径
      },
    },
  })),

  // 自定义规则(可按需添加)
  {
    rules: {
      "@typescript-eslint/no-unused-vars": "error",
      "@typescript-eslint/no-var-requires": "error",
    },
  },
];

3. 添加基础TS配置文件

ESLint解析TS文件需要依赖tsconfig.json,项目根目录创建该文件(基础配置即可):

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["**/*.ts"],
  "exclude": ["node_modules"]
}

4. 测试效果

重新执行npx eslint .,此时ESLint会正确检测app.ts中的问题,比如:

  • greet函数的name参数未声明类型(@typescript-eslint/no-implicit-any)
  • 混合使用import和require(@typescript-eslint/no-var-requires)
  • num1变量未被使用(@typescript-eslint/no-unused-vars)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:00:15