如何在angular度2中使用codelyzer

我想在我的项目中使用codelyzer,我使用systemjs和没有webpack。 我添加了一个tslint到我的项目,并使用npm开始运行项目,但它没有从我的项目中得到任何错误,即使我没有在我的项目中使用正确的风格指南我该怎么做使用codelyzer?

Codelyzer已经可以在http://codelyzer.com上在线了,所以你可以在浏览器中试试!

你也可以用它来:

Angular CLI

Angular CLI支持codelyzer。 为了使用CLIvalidation你的代码和自定义的Angular特定规则,只需使用:

ng new codelyzer ng lint 

请注意,默认情况下,所有组件都与样式指南alignment,因此您不会在控制台中看到任何错误。

有angular的种子

另外一个与代码合成器一体化的项目是angular度种子 ( 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 

请注意,默认情况下,所有组件都与样式指南alignment,因此您不会在控制台中看到任何错误。

自定义设置

您可以使用自定义设置轻松使用codelyzer:

安装

 npm i codelyzer tslint typescript @angular/core@2.0.2 @angular/compiler@2.0.2 rxjs@5.0.0-beta.12 zone.js@0.6.21 

现在在node_modules目录所在的位置创build以下tslint.json文件:

 { "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和以下内容的同一目录中创build组件文件:

 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". 

编辑器configuration

请注意,您需要在您的编辑器上安装tslint插件

Codelyzer应该开箱即用,但是对于VSCode,您将需要打开Code > Preferences > User Settings ,然后input以下configuration:

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

现在你应该有以下结果:

VSCode Codelyzer