【问题标题】:Avoid error 'The selector of the component should be named kebab-case and include dash '避免错误“组件的选择器应命名为 kebab-case 并包含破折号”
【发布时间】:2017-12-09 09:07:53
【问题描述】:

如果我不想重命名选择器,如何避免错误“组件的选择器应命名为 kebab-case 并在 Angular2 中包含破折号”?有什么解决办法吗?..

【问题讨论】:

    标签: angular tslint


    【解决方案1】:

    试试

    import {CUSTOM_ELEMENTS_SCHEMA} from "@angular/core";
    
    @NgModule({
        schemas: [
            CUSTOM_ELEMENTS_SCHEMA
        ]
    })
    

    【讨论】:

    【解决方案2】:

    此错误是由 TSLint 使用 codelyzer 插件生成的。这会强制执行针对选择器的 Angular 样式指南建议:https://angular.io/guide/styleguide#component-selectors

    与大多数 linting 错误一样,有一些方法可以配置或忽略它们。一定要慎重考虑如何以及何时忽略掉毛错误。根据您的情况,您可能希望以不同的方式处理此错误:

    • 如果您的所有组件都有此错误,并且有匹配的选择器,您可以更改 TSLint 用于检查 TSLint.json 文件中的错误的规则:

      {
        "rules": {
          // The rules component-selector and directive-selector have the following arguments:
          // [ENABLED, "attribute" | "element", "prefix" | ["listOfPrefixes"], "camelCase" | "kebab-case"]
          "component-selector": [true, "element", ["cmp-prefix1", "cmp-prefix2"], "kebab-case"],
          "directive-selector": [true, "attribute", ["dir-prefix1", "dir-prefix2"], "camelCase"],
          ...
        }
      }
      

      https://github.com/mgechev/codelyzer#recommended-configuration

      您还可以配置 CLI 以在 angular.json 文件的底部生成具有正确前缀的组件和指令:

      {
        "schematics": {
          "@schematics/angular:component": {
            "inlineStyle": false,
            "inlineTemplate": false,
            "prefix": "myCustomPrefix",
            "styleext": "scss"
        },
        "@schematics/angular:directive": {
          "prefix": "myCustomPrefix"
        }
      }
      
    • 如果你有一个一次性的组件或指令,你想从检查中排除 TSLint,你可以使用抑制注释:

      // tslint:disable-next-line:component-selector
      
    • 如果您想完全禁用此检查,您可以在tslint.json 中这样做:

      {
        "rules": {
          "directive-selector": false,
          "component-selector": false,
          ...
        }
      }
      

    【讨论】:

    • 我不会对每个组件都这样做。它看起来很烦人而且很冗长。因此,如果您不想有前缀,只需转到tslint.json 并关闭相应的规则即可。在这种特殊情况下,将 "component-selector": [false, ... ] 的值从 true 更改为 false
    • @hastrb 同意。我已经更新了我的答案。感谢您的评论!
    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 2015-03-27
    • 2015-05-28
    • 2021-10-24
    • 2017-06-03
    • 2019-01-10
    • 2018-11-25
    • 2016-07-16
    相关资源
    最近更新 更多