網站搜尋

angular - 有沒有一個 eslint 規則可以檢測未使用的類屬性?


我正在處理一個 Angular 專案,而我的 ESLint 設定無法檢測到私有類別變數未被使用,例如。

@Component{...}
export class ExampleComponent {
  private exampleProperty: string
}

上方的私有屬性 - exampleProperty 在我目前的 ESLint 設定下不會被標示。

我的 .eslintrc.json:

{
  "root": true,
  "ignorePatterns": ["projects/**/*"],
  "overrides": [
    {
      "files": ["*.ts"],
      "parserOptions": {
        "project": ["tsconfig.json", "e2e/tsconfig.json"],
        "createDefaultProgram": true
      },
      "env": { "browser": true, "jest": true },
      "extends": [
        "eslint:recommended",
        "plugin:@angular-eslint/recommended",
        "plugin:@angular-eslint/template/process-inline-templates",
        "plugin:@typescript-eslint/recommended"
      ],
      "rules": {
        "@angular-eslint/component-selector": [
          "error",
          { "prefix": "app", "style": "kebab-case", "type": "element" }
        ],
        "@angular-eslint/no-host-metadata-property": "off",
        "@typescript-eslint/ban-ts-comment": "off",
        "@typescript-eslint/ban-types": "off",
        "@typescript-eslint/explicit-module-boundary-types": "off",
        "@typescript-eslint/no-explicit-any": "off",
        "@typescript-eslint/no-unused-vars": [
          "error",
          { "argsIgnorePattern": "^_" }
        ],
        "no-case-declarations": "off",
        "no-console": ["error", { "allow": ["warn", "error"] }],
        "no-prototype-builtins": "off",
        "no-unused-vars": "off"
      }
    },
    {
      "files": ["*.html"],
      "extends": ["plugin:@angular-eslint/template/recommended"],
      "rules": {}
    }
  ]
}

我該如何讓程式碼檢查工具檢測到這個?

答案#1

你可以透過在 tsconfig.json 中開啟 noUnusedLocals 選項,讓 TypeScript 幫你抓到這個問題。(「Locals」顯然也包含未使用的私有屬性,畢竟它們是類別的本地成員。)

這裡有一個啟用該選項的類別的遊樂場,它會產生以下錯誤:

‘exampleProperty’ 已宣告,但其值從未被讀取。(6133)

(我新增了一個建構函式並設定了屬性,只是為了避免錯誤與尚未初始化的錯誤混淆或被掩蓋。)

答案#2

如果你使用真正的 # 私有類別欄位,核心 ESLint 規則 no-unused-private-class-members 將會檢測未使用的欄位。

對於 TypeScript 的 private 類型隱私,目前沒有這樣的規則。但有一個開放的 typescript-eslint 問題,用於增強 no-unused-private-class-members,並且正在接受 PR。意思是:如果你能正確編碼,它將被接受到 typescript-eslint 中。