6.0.2 • Published 4 years ago

codelyzer v6.0.2

Weekly downloads
1,484,315
License
MIT
Repository
github
Last release
4 years ago

npm version Downloads Build Status code style: prettier Conventional Commits Gitter Chat

codelyzer

A set of tslint rules for static code analysis of Angular TypeScript projects.
(If you are using ESLint check out the new angular-eslint repository.)

You can run the static code analyzer over web apps, NativeScript, Ionic, etc.

Vote for your favorite feature here. For more details about the feature request process see this document

npm.io

How to use?

Angular CLI

Angular CLI has support for codelyzer. In order to validate your code with CLI and the custom Angular specific rules just use:

ng new codelyzer
ng lint

Note that by default all components are aligned with the style guide so you won't see any errors in the console.

Angular Seed

Another project which has out of the box integration with codelyzer is angular-seed. In order to run the linter you should:

# 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

Note that by default all components are aligned with the style guide so you won't see any errors in the console.

Custom Setup

Preset

You can use the tslint-angular preset. All you need is:

npm i tslint-angular

After that create a tslint.json file with the following configuration:

{
  "extends": ["tslint-angular"]
}

Run the linter with:

./node_modules/.bin/tslint -c tslint.json

TSLint will now complain that there are rules which require type checking. In order to fix this, use the -p config option:

./node_modules/.bin/tslint -p tsconfig.json -c tslint.json

Custom Installation

You can easily use codelyzer with your custom setup:

npm i codelyzer tslint @angular/compiler @angular/core

A. Using codelyzer package in PATH

Create the following tslint.json file like:

{
  "extends": ["codelyzer"],
  "rules": {
    "component-class-suffix": true,
    "component-max-inline-declarations": true,
    "component-selector": [true, "element", "sg", "kebab-case"],
    "contextual-lifecycle": true,
    "directive-class-suffix": true,
    "directive-selector": [true, "attribute", "sg", "camelCase"],
    "no-attribute-decorator": true,
    "no-conflicting-lifecycle": true,
    "no-forward-ref": true,
    "no-host-metadata-property": true,
    "no-input-rename": true,
    "no-inputs-metadata-property": true,
    "no-lifecycle-call": true,
    "no-output-native": true,
    "no-output-on-prefix": true,
    "no-output-rename": true,
    "no-outputs-metadata-property": true,
    "no-pipe-impure": true,
    "no-queries-metadata-property": true,
    "no-unused-css": true,
    "prefer-inline-decorator": true,
    "prefer-output-readonly": true,
    "template-banana-in-box": true,
    "template-conditional-complexity": [true, 4],
    "template-cyclomatic-complexity": [true, 5],
    "template-i18n": [true, "check-id", "check-text"],
    "template-no-negated-async": true,
    "template-use-track-by-function": true,
    "use-component-selector": true,
    "use-component-view-encapsulation": true,
    "use-lifecycle-interface": true,
    "use-pipe-transform-interface": true
  }
}

To run TSLint with this setup you can use one of the following alternatives:

  1. Install codelyzer globally npm install -g codelyzer

  2. Run TSLint from a package.json script by adding a script like tslint . to your package.json, similar to:

"scripts": {
  ...
  "lint": "tslint .",
  ...
},

Then run npm run lint

B. Using codelyzer from node_modules directory

Now create the following tslint.json file where your node_modules directory is:

{
  "rulesDirectory": ["node_modules/codelyzer"],
  "rules": {
    "component-class-suffix": true,
    "component-max-inline-declarations": true,
    "component-selector": [true, "element", "sg", "kebab-case"],
    "contextual-lifecycle": true,
    "directive-class-suffix": true,
    "directive-selector": [true, "attribute", "sg", "camelCase"],
    "no-attribute-decorator": true,
    "no-conflicting-lifecycle": true,
    "no-forward-ref": true,
    "no-host-metadata-property": true,
    "no-input-rename": true,
    "no-inputs-metadata-property": true,
    "no-lifecycle-call": true,
    "no-output-native": true,
    "no-output-on-prefix": true,
    "no-output-rename": true,
    "no-outputs-metadata-property": true,
    "no-pipe-impure": true,
    "no-queries-metadata-property": true,
    "no-unused-css": true,
    "prefer-inline-decorator": true,
    "prefer-output-readonly": true,
    "template-banana-in-box": true,
    "template-conditional-complexity": [true, 4],
    "template-cyclomatic-complexity": [true, 5],
    "template-i18n": [true, "check-id", "check-text"],
    "template-no-negated-async": true,
    "template-use-track-by-function": true,
    "use-component-selector": true,
    "use-component-view-encapsulation": true,
    "use-lifecycle-interface": true,
    "use-pipe-transform-interface": true
  }
}

Next you can create a component file in the same directory with name component.ts and the following content:

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

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

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

As last step you can execute all the rules against your code with tslint:

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

You should see the following output:

component.ts[4, 13]: The selector of the component "Codelyzer" should have prefix "sg" (https://goo.gl/cix8BY)
component.ts[12, 3]: Implement lifecycle hook interface OnInit for method ngOnInit in class Codelyzer (https://goo.gl/w1Nwk3)
component.ts[9, 7]: The name of the class Codelyzer should end with the suffix Component (https://goo.gl/5X1TE7)

Editor Configuration

Note that you need to have tslint plugin install on your editor.

Codelyzer should work out of the box with Atom but for VSCode you will have to open Code > Preferences > User Settings, and enter the following config:

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

Now you should have the following result:

VSCode Codelyzer

Enjoy!

Changelog

You can find it here.

Recommended configuration

Below you can find a recommended configuration which is based on the Angular Style Guide.

{
  // 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"],

  "component-max-inline-declarations": true,
  "contextual-lifecycle": true,
  "no-conflicting-lifecycle": true,
  "no-host-metadata-property": true,
  "no-input-rename": true,
  "no-inputs-metadata-property": true,
  "no-output-native": true,
  "no-output-on-prefix": true,
  "no-output-rename": true,
  "no-outputs-metadata-property": true,
  "no-queries-metadata-property": true,
  "prefer-inline-decorator": true,
  "template-banana-in-box": true,
  "template-no-negated-async": true,
  "use-lifecycle-interface": true,
  "use-pipe-transform-interface": true,

  // The rules component-class-suffix and directive-class-suffix have the following arguments:
  // [ENABLED, "suffix" | ["listOfSuffixes"]]
  // Where "suffix" is/are your custom(s) suffix(es), for instance "Page" for Ionic components.
  "component-class-suffix": [true, "Component"],
  "directive-class-suffix": [true, "Directive"]
}

Rules Status

RuleStatus
component-class-suffixStable
component-max-inline-declarationsStable
component-selectorStable
contextual-decoratorStable
contextual-lifecycleStable
directive-class-suffixStable
directive-selectorStable
import-destructuring-spacingStable
no-attribute-decoratorStable
no-forward-refStable
no-host-metadata-propertyStable
no-input-prefixStable
no-input-renameStable
no-inputs-metadata-propertyStable
no-lifecycle-callStable
no-output-nativeStable
no-output-on-prefixStable
no-output-renameStable
no-outputs-metadata-propertyStable
no-pipe-impureStable
no-queries-metadata-propertyStable
prefer-inline-decoratorStable
prefer-output-readonlyStable
template-banana-in-boxStable
template-cyclomatic-complexityStable
template-no-call-expressionStable
template-no-negated-asyncStable
template-use-track-by-functionStable
use-component-selectorStable
use-component-view-encapsulationStable
use-lifecycle-interfaceStable
use-pipe-decoratorStable
use-pipe-transform-interfaceStable
prefer-on-push-component-change-detectionExperimental
no-conflicting-lifecycleExperimental
no-unused-cssExperimental
pipe-prefixExperimental
relative-url-prefixExperimental
template-accessibility-alt-textExperimental
template-accessibility-elements-contentExperimental
template-accessibility-label-forExperimental
template-accessibility-tabindex-no-positiveExperimental
template-accessibility-table-scopeExperimental
template-accessibility-valid-ariaExperimental
template-click-events-have-key-eventsExperimental
template-conditional-complexityExperimental
template-i18nExperimental
template-mouse-events-have-key-eventsExperimental
template-no-anyExperimental
template-no-autofocusExperimental
template-no-distracting-elementsExperimental
angular-whitespaceDeprecated

Disable a rule that validates Template or Styles

Lint rules can be disabled by adding a marker in TypeScript files. More information here.

To disable rules that validate templates or styles you'd need to add a marker in the TypeScript file referencing them.

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

/* tslint:disable:template-use-track-by-function */
@Component({
  selector: 'codelyzer',
  templateUrl: './codelyzer.component.html',
})
class Codelyzer {}

Advanced configuration

Codelyzer supports any template and style language by custom hooks. If you're using Sass for instance, you can allow codelyzer to analyze your styles by creating a file .codelyzer.js in the root of your project (where the node_modules directory is). In the configuration file can implement custom pre-processing and template resolution logic:

// Demo of transforming Sass styles
var sass = require('node-sass');

module.exports = {
  // Definition of custom interpolation strings
  interpolation: ['{{', '}}'],

  // You can transform the urls of your external styles and templates
  resolveUrl(url, decorator) {
    return url;
  },

  // Transformation of the templates. This hooks is quite useful
  // if you're using any other templating language, for instance
  // jade, markdown, haml, etc.
  //
  // NOTE that this method WILL NOT throw an error in case of invalid template.
  //
  transformTemplate(code, url, decorator) {
    return { code: code, url: url };
  },

  // Transformation of styles. This hook is useful is you're using
  // any other style language, for instance Sass, Less, etc.
  //
  // NOTE that this method WILL NOT throw an error in case of invalid style.
  //
  transformStyle(code, url, decorator) {
    var result = { code: code, url: url };
    if (url && /\.scss$/.test(url)) {
      var transformed = sass.renderSync({ data: code, sourceMap: true, outFile: '/dev/null' });
      result.source = code;
      result.code = transformed.css.toString();
      result.map = transformed.map.toString();
    }
    return result;
  },

  // Custom predefined directives in case you get error for
  // missing property and you are using a template reference
  predefinedDirectives: [{ selector: 'form', exportAs: 'ngForm' }],

  // None = 0b000, Error = 0b001, Info = 0b011, Debug = 0b111
  logLevel: 0b111,
};

Contributors

mgechevwKozarafaelss95preslavshmohammedzamakhanrokerkony
GregOnNetalan-agius4kevinphelpseppsiloncsvnghsyeung
Kobzolmattlewis92lazarljubenovicsagittarius-revconnor4312Foxandxss
gbilodeauNagRockHotellMartin-Wegnercomfroelsplantain-00
nexus-uwalexkpekloktionov129alisd23aboytonbmvantunes
MoerikisneasEmmanuelDemeyeromanoMandurokarol-depka
leosvelperezmuhammadghazaliPapsOurwlogelrobzenn92rtfpessoa
santoshyadav198613scttcperstschaketmairYogliBcexbrayat
clydinreducktedsomeblue

License

MIT

@qulix/tslint-config-angularng-horocom.d3sd1.angular.multiplaformangular-multiplatform@poui/tslint@piratuks/lint-code-styledashboard-sharedkup.common.util@ngxa/ruleso3-dapi-n3@cknow/codelyzer-config@yokots/tslint-config-angularionic-v4-migration-tslinttslint-config-pedantic@kidwen/eslint-angulareslint-config-helmng2-lib-proj@everything-registry/sub-chunk-1350@puzzleitc/frontend-guidestable-app-libwebdevkit-gugwerk85-tslint-rulessabium-frameworkshared-tslint-config-wrebird-https-letsencryptrebel-con-dev-depsrg-npm-devrms-sparklinesreyesoft-citestlogintestlogin1testlogin2testlogin3testlogin4vk-libraries@dlwlrma/tslint-config-angularmindful-playlist-managerloading-infolbdynamicirstea-typescript-configma-tslintmadlogingss-consumer-qa-automationh21-tslint-ruleslc-easyforms-ng2ghs-umami-tonkotsu-curator-devtoolsmyapp19masterngontimize-web-ngx-library-toolspoke-try-hardpoke-try-harderns-packageo3-dapi-neo3ngx-lintng-search-dropdownngmigrateng-pipeng2-accordionsng2-tree-ap68ng-softrustngrx-kitng-ssrng-valleyng2-button-loaderng2-preloaderngslplanavsky-core-designpi-libpme-login-modulengx-webpackngx-tooltip-serverpgs-dev-tslintqms-automation-testing-21sprout-web-uisunilogin2sumlogin2ro-dev-utilsslides-render-angularslides-render-angular-tailwindcssslides-findertslint-magaya-angulartslint-specstslint-rule-primeng-pbutton-disallow-click-eventtslint-config-kaskotslint-ext12tslint-config-elgervbui-framework-app-angular-devuiguy-baseprojecttns-template-find-a-doctor-ngts-config-mobiquity-angular@amaplex-software/amaplex-angular-tslint-config@armor/tslint-armor-standard@arcbees/tslint@ae-scripts/gulp-angular@alexkunin/dev-tslint-angular@balinj/build@beeman/scully@blackbaud/skyux-builder@blackbaud-bobbyearl/skyux-builder@bixi/lint
6.0.2

4 years ago

6.0.1

4 years ago

6.0.0

4 years ago

6.0.0-next.2

4 years ago

6.0.0-next.0

5 years ago

6.0.0-next.1

5 years ago

5.2.2

5 years ago

5.2.1

5 years ago

5.2.0

5 years ago

5.1.2

5 years ago

5.1.1

5 years ago

5.1.0

6 years ago

5.0.1

6 years ago

5.0.0

6 years ago

5.0.0-beta.2

6 years ago

5.0.0-beta.1

6 years ago

5.0.0-beta.0

6 years ago

4.5.0

6 years ago

4.4.4

6 years ago

4.4.3

6 years ago

4.4.2

6 years ago

4.4.1

6 years ago

4.4.0

6 years ago

4.3.0

7 years ago

4.2.1

7 years ago

4.2.0

7 years ago

4.1.0

7 years ago

4.0.2

7 years ago

4.0.1

7 years ago

4.0.0

7 years ago

3.2.2

7 years ago

3.2.1

7 years ago

3.2.0

7 years ago

3.1.2

7 years ago

3.1.1

7 years ago

3.1.0

7 years ago

3.0.1

8 years ago

3.0.0

8 years ago

2.1.1

8 years ago

2.1.0

8 years ago

3.0.0-beta.4

8 years ago

3.0.0-beta.3

8 years ago

3.0.0-beta.2

8 years ago

3.0.0-rc.2

8 years ago

3.0.0-beta.1

8 years ago

3.0.0-beta.0

8 years ago

2.0.1

8 years ago

2.0.0

8 years ago

2.0.0-beta.4

8 years ago

2.0.0-beta.3

8 years ago

2.0.0-beta.2

8 years ago

2.0.0-beta.1

8 years ago

2.0.0-beta.0

8 years ago

1.0.0-beta.4

8 years ago

1.0.0-beta.3

8 years ago

1.0.0-beta.2

8 years ago

1.0.0-beta.1

8 years ago

1.0.0-beta.0

8 years ago

0.0.28

8 years ago

0.0.27

8 years ago

0.0.26

8 years ago

0.0.25

8 years ago

0.0.24

8 years ago

0.0.23

9 years ago

0.0.22

9 years ago

0.0.21

9 years ago

0.0.20

9 years ago

0.0.19

9 years ago

0.0.18

9 years ago

0.0.17

9 years ago

0.0.16

9 years ago

0.0.15

9 years ago

0.0.14

9 years ago

0.0.13

9 years ago

0.0.12

9 years ago

0.0.11

9 years ago

0.0.10

9 years ago

0.0.0

9 years ago