eslint 为角度库注册自定义前缀:选择器应以这些前缀之一开头,

afr*_*111 7 eslint angular

我有一个 Angular 12 解决方案,它有两个项目:一个是库,另一个是应用程序。我将它们从使用 tslint 转换为 eslint。我使用了以下命令:

ng add @angular-eslint/schematics

ng g @angular-eslint/schematics:convert-tslint-to-eslint my-app

ng g @angular-eslint/schematics:convert-tslint-to-eslint my-library

我的库使用与应用程序不同的前缀。当我运行时,ng lint出现以下错误:

The selector should start with one of these prefixes: "app" (https://angular.io/guide/styleguide#style-02-07) @angular-eslint/component-selector

.eslintrc.json我在应用程序和库的根目录和顶部项目目录中有一个文件。我尝试将组件选择器前缀的条目更改为lib库项目文件夹中的 .eslintrc.json 文件:

   "@angular-eslint/component-selector": [
          "error",
          {
            "type": "element",
            "prefix": "lib",
            "style": "kebab-case"
          }
        ]
      }
Run Code Online (Sandbox Code Playgroud)

这并不能解决问题。如何为我的库注册自定义前缀才能消除此错误?

Tob*_*san 7

还有一个@angular-eslint/directive-selector适用于指令的条目。因此,如果您在指令而不是组件上收到该 linting 错误,请尝试更新prefix上的@angular-eslint/directive-selector

此外,我假设组件中的选择器以lib-. 如果没有,那么您需要替换lib为您使用的前缀。

例如,假设您的组件和指令选择器如下所示 - 请注意 的前缀lib-

@Component({
  selector: 'lib-search',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
Run Code Online (Sandbox Code Playgroud)

我们还假设您的指令选择器如下所示 - 请注意 的前缀lib

@Directive({
  selector: '[libFormatSomething]',
  providers: [MyFormatterService]
})
Run Code Online (Sandbox Code Playgroud)

使用上述假设,以下是运行该命令后为我生成的.eslintrc.json的完整示例:

{
  "root": true,
  "ignorePatterns": [
    "projects/**/*"
  ],
  "overrides": [
    {
      "files": [
        "*.ts"
      ],
      "parserOptions": {
        "project": [
          "tsconfig.json",
          "e2e/tsconfig.json"
        ],
        "createDefaultProgram": true
      },
      "extends": [
        "plugin:@angular-eslint/recommended",
        "plugin:@angular-eslint/template/process-inline-templates"
      ],
      "rules": {
        "@angular-eslint/component-selector": [
          "error",
          {
            "prefix": "lib",
            "style": "kebab-case",
            "type": "element"
          }
        ],
        "@angular-eslint/directive-selector": [
          "error",
          {
            "prefix": "lib",
            "style": "camelCase",
            "type": "attribute"
          }
        ]
      }
    },
    {
      "files": [
        "*.html"
      ],
      "extends": [
        "plugin:@angular-eslint/template/recommended"
      ],
      "rules": {}
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)