【问题标题】:How can I remove unused imports/declarations from the entire project of React Typescript?如何从 React Typescript 的整个项目中删除未使用的导入/声明?
【发布时间】:2021-01-29 13:37:18
【问题描述】:

我正在尝试删除this SO thread 中为Angular 回答的未使用的导入和声明。我正在尝试使用eslint-plugin-react 来实现目标,但没有找到任何选项来使用单个命令从整个项目中删除未使用的导入和声明。

这是我的 .eslintrc.json

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 12
    },
    "plugins": [
        "react",
        "@typescript-eslint",
        "unused-imports"
    ],
    "rules": {
        "indent": [
            "warn",
            "tab"
        ],
        "linebreak-style": [
            "warn",
            "windows"
        ],
        "quotes": [
            "warn",
            "double"
        ],
        "semi": [
            "warn",
            "always"
        ],
        "@typescript-eslint/no-unused-vars": "on",
        "unused-imports/no-unused-imports-ts": "on"
    }
}

或者有没有办法在 VS Code 中使用 ESLint 或 Typescript Hero 扩展来做同样的事情?

【问题讨论】:

    标签: reactjs typescript visual-studio-code eslint


    【解决方案1】:

    如果需要快速且无需额外努力,您还可以在 VSCode 中使用快捷方式:

    Option + Shift + O 用于 Mac

    Alt + Shift + O 用于 Windows

    【讨论】:

      【解决方案2】:

      TL;DR

      使用unused-imports/no-unused-imports 代替no-unused-vars 作为规则名称。


      如果您使用的是 ESLint 版本 eslint-plugin-unused-imports,您可能需要将规则名称更改为 unused-imports/no-unused-imports 而不是总括 no-unused-vars

      {
          "rules": {
              "unused-imports/no-unused-imports": "error"
          }
      }
      

      详细使用请参考the author's GitHub

      对我来说,no-unused-var 没有附带自动修复程序(它只会提到错误/警告的数量,但是当我切换到 unused-imports/no-unused-imports 时,所有问题都是自动固定。

      【讨论】:

        【解决方案3】:

        使用unused-imports 插件和unused-imports/no-unused-imports-ts 规则,eslint --fix 将删除imports。

        这是一个示例 repo,--fix 删除了未使用的 imports。

        https://github.com/moshfeu/eslint-ts-unused-imports

        旧答案

        eslint 有一个内置的 fix 选项。

        eslint ... --fix
        

        如果rules 包含no-unused-vars,eslint 将通过删除它们(以及其他auto fixes)来“修复”未使用的导入。

        【讨论】:

        • 好的,能否请您补充一下eslint的正确配置?
        • 抱歉,不清楚。我已经更新了我的答案。如果现在更清楚,请告诉我。
        • 很高兴 :) 如果它回答了您的问题,请接受它,以便对其他人有所帮助。谢谢。
        • no-unused-vars 规则实际上没有可用的自动修复程序。默认情况下不会删除导入。
        • @MoshFeu - 你的回答是no-unused-vars,但你的示例仓库使用unused-imports/no-unused-imports-ts(与--fix一起使用)
        猜你喜欢
        • 2019-12-03
        • 2014-06-19
        • 2020-07-29
        • 2021-07-09
        • 2019-08-09
        • 2012-12-22
        • 2023-03-03
        • 2022-10-05
        • 2019-01-20
        相关资源
        最近更新 更多