Подтвердить что ты не робот

Как использовать codelyzer в angular 2

Я хочу использовать codelizer в моем проекте, и я использую systemjs и не webpack. Я добавил этот tslint в мой проект и использовал npm для запуска проекта, но он не получил никаких ошибок из моего проекта, хотя я didn Не используйте правильный стиль в моем проекте что я должен делать, чтобы использовать codelizer?

4b9b3361

Ответ 1

Codelyzer уже доступен на сайте http://codelyzer.com, поэтому вы можете попробовать его в своем браузере!

Вы также можете использовать его в:

Angular CLI

В Angular CLI есть поддержка codelyzer. Для проверки вашего кода с помощью CLI и пользовательских правил Angular просто используйте:

ng new codelyzer
ng lint

Обратите внимание, что по умолчанию все компоненты выровнены по руководству по стилю, поэтому вы не увидите никаких ошибок в консоли.

Угловое семя

Еще один проект, который имеет встроенную интеграцию с codelyzer, это angular-seed. Для запуска линтера необходимо:

# Skip if you've already cloned Angular Seed
git clone https://github.com/mgechev/angular-seed

# Skip if you've already installed all the dependencies of Angular Seed
cd angular-seed && npm i

# Run all the tslint and codelyzer rules
npm run lint

Обратите внимание, что по умолчанию все компоненты выровнены по руководству по стилю, поэтому вы не увидите никаких ошибок в консоли.

Пользовательская настройка

Вы можете легко использовать codelyzer с вашей пользовательской настройкой:

Монтаж
npm i codelyzer tslint typescript @angular/[email protected] @angular/[email protected] [email protected] [email protected]

Теперь создайте следующий файл tslint.json, где находится ваш каталог node_modules:

{
  "rulesDirectory": [
    "node_modules/codelyzer"
  ],
  "rules":{
    "directive-selector-name": [true, "camelCase"],
    "component-selector-name": [true, "kebab-case"],
    "directive-selector-type": [true, "attribute"],
    "component-selector-type": [true, "element"],
    "directive-selector-prefix": [true, "sg"],
    "component-selector-prefix": [true, "sg"],
    "use-input-property-decorator": true,
    "use-output-property-decorator": true,
    "use-host-property-decorator": true,
    "no-attribute-parameter-decorator": true,
    "no-input-rename": true,
    "no-output-rename": true,
    "no-forward-ref": true,
    "use-life-cycle-interface": true,
    "use-pipe-transform-interface": true,
    "pipe-naming": [true, "camelCase", "sg"],
    "component-class-suffix": true,
    "directive-class-suffix": true,
    "import-destructuring-spacing": true,
    "templates-use-public": true,
    "no-access-missing-member": true,
    "invoke-injectable": true
  }
}

Затем вы можете создать файл компонента в том же каталоге с именем component.ts и следующим содержимым:

import { Component } from '@angular/core';

@Component({
  selector: 'codelyzer',
  template: '
    <h1>Hello {{ nme }}!</h1>
  '
})
class Codelyzer {
  name: string = 'World';

  ngOnInit() {
    console.log('Initialized');
  }
}

В качестве последнего шага вы можете выполнить все правила для своего кода с помощью tslint:

$ ./node_modules/.bin/tslint -c tslint.json component.ts

Вы должны увидеть следующий вывод:

component.ts[4, 13]: The selector of the component "Codelyzer" should have prefix "sg"
component.ts[12, 3]: Implement lifecycle hook interface OnInit for method ngOnInit in class Codelyzer
component.ts[9, 7]: The name of the class Codelyzer should end with the suffix Component
component.ts[6, 18]: The property "nme" that you're trying to access does not exist in the class declaration. Probably you mean: "name".

Конфигурация редактора

Обратите внимание, что в вашем редакторе должен быть установлен плагин tslint.

Codelyzer должен работать из коробки с Atom, но для VSCode вам придется открыть Code > Preferences > User Settings и ввести следующую конфигурацию:

{
  "tslint.rulesDirectory": "./node_modules/codelyzer",
  "typescript.tsdk": "node_modules/typescript/lib"
}

Теперь у вас должен быть следующий результат:

VSCode Codelyzer
(источник: gifyu.com)