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

Eslint no-unused-vars未检测到导出未使用变量问题排查

问题:ESLint未检测到未使用的导出变量

我编写了如下代码:

const notUsed = 1;
export const notUsedExported = 1;

这两个常量均未被使用,但运行ESLint时仅未导出的notUsed触发了no-unused-vars错误,导出的notUsedExported未被检测到。我希望该导出未使用变量也能触发错误,我的ESLint配置如下:

{
  "extends": [
    "eslint:recommended",
    "semistandard",
    "plugin:jest/recommended"
  ],
  "env": {
    "es2019": true,
    "jest": true,
    "mocha": true,
    "node": true
  },
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "rules": {
    "array-callback-return": "warn",
    "camelcase": "warn",
    "guard-for-in": "off",
    "jest/no-conditional-expect": "warn",
    "jest/no-disabled-tests": "warn",
    "jest/no-focused-tests": "error",
    "jest/no-identical-title": "error",
    "jest/no-mocks-import": "warn",
    "n/no-path-concat": "off",
    "no-await-in-loop": "off",
    "no-case-declarations": "off",
    "no-console": "warn",
    "no-continue": "off",
    "no-control-regex": "warn",
    "no-empty-pattern": "off",
    "no-mixed-operators": "warn",
    "no-param-reassign": "off",
    "no-restricted-syntax": "off",
    "no-throw-literal": "warn",
    "no-underscore-dangle": "off",
    "no-unsafe-optional-chaining": "warn",
    "no-useless-escape": "warn",
    "prefer-regex-literals": "off",
    "promise/param-names": "off",
    "no-unused-vars": "error"
  }
}

原因分析

ESLint的no-unused-vars规则默认不会标记导出的变量为未使用,因为规则的设计逻辑是:导出的变量通常会被其他模块引用,所以默认忽略对它们的未使用检查。当前配置仅将no-unused-vars设为error,未修改默认的导出变量检测行为,加上继承的semistandard配置也未调整该规则,因此导出的notUsedExported不会触发错误。

解决方案

需要显式配置no-unused-vars规则的exported选项,让ESLint检查所有导出的变量。修改配置中的no-unused-vars规则如下:

"no-unused-vars": ["error", {
  "vars": "all",
  "args": "after-used",
  "ignoreRestSiblings": false,
  "exported": "all"
}]

其中exported: "all"会让ESLint对所有导出的变量进行未使用检查,不管是命名导出还是默认导出,只要没有被使用就会触发no-unused-vars错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:40:38