TsLint Custom rules creation and configuration

1.    Custom rules:

TsLint ships with a set of core rules that can be configured. However, users are also allowed to write their own rules, which allows them to enforce specific behaviour not covered by the core of TsLint.

2. Why Custom rules:

  1. It will help to automate Code review up to some extent.

e.g.  Sometimes developers forget to remove fdescribe/fit from spec files before merging it to develop branch. There is a possibility it can be missed by the reviewer as well.

If we add one custom rule in TsLint to identify fdescribe or fit, we can restrict the user to merge corrupt code to develop branch.

2. It will give you more control over the standards of your codebase. You can set new standards suggested by clients.

3. Important conventions to create custom rules:

  • Rule identifiers are always kebab-cased.
  • Rule files are always camel-cased (camelCasedRule.ts).
  • Rule files must contain the suffix Rule.
  • The exported class must always be named Rule and extend from Lint.Rules.AbstractRule.

1.    Steps to create Custom Rules:

There are two approaches to create custom rules:

  • TSQuery approach.
  • AST approach.

We are covering TSQuery approach in this document:

I. Create a class with name Rule extends Rules.AbstractRule.

export class Rule extends Rules.AbstractRule { 
}

II. Override apply the method of base class. Apply method is a link between TsLinter and custom rule. It takes sourceFile as input parameter and Array of failures as output.

export class Rule extends Rules.AbstractRule {
      public apply (sourceFile: SourceFile): Array<RuleFailure> { 
       }
}

SourceFile is an object of AST it can be referred to a starting point of AST(abstract syntax tree).

III. TSQuery of Rule : Below query will filter out files containing fdescribe or fit.

const FDESCRIBE_FIT_QUERY = 'CallExpression >1Identifier[name=/^f(describe|it)$/]'; 

IV. Complete Rule class using TSQuery approach will look like below :

5.    Configuration of custom Rule in TsLint:

I. Create your custom rule directory and add your custom rule class into it.

II.  Compile your custom rule class with below command, Compiled JavaScript file will be created.:

 tsc --lib es2015 noFdescribeRule.ts 

III. Provide your directory name in tslint.json=> rulesDirectory section and add your rule in rules section :

Rule name is inferred automatically from Custom rule class Name:

noFdescribeRule => no-fdescribe

IV. Custom rule is now configured in your application’s TsLint.

Contribute by :

This article is contribute by Ajay Srivastava. He is having very good experience in multiple technologies & also a good mentor. For more information about him, please click here..

References:

For more information refer below links:

  1. https://palantir.github.io/tslint/develop/custom-rules/
  2. https://medium.com/@phenomnominal/custom-typescript-lint-rules-with-tsquery-and-tslint-144184b6ff2d

Leave a Reply