Creating Custom Eslint Rules. How to use Eslint like a pro | by Babatunde Koiki | Feb, 2022

How you can use Eslint like a professional

A gavel
Picture by Tingey Injury Law Firm on Unsplash

ESLint is a static code evaluation instrument for figuring out problematic patterns present in JavaScript code. Nicholas C. Zakas created it in 2013. ESLint guidelines are configurable, and customised guidelines could be outlined and loaded.

ESLint covers each code high quality and coding model points — Wikipedia. In easy phrases, ESLint is a code evaluation instrument used for code formatting, error checking, imposing code kinds, amongst others. It’s used to implement code kinds throughout a undertaking. There are a few customary code kinds in ESLint. These codecs and kinds are known as guidelines.

This article will clarify the best way to create your personal customized ESLint guidelines and create a script with the ESLint module that will probably be used to lint recordsdata.

We’ll be making a easy TypeScript undertaking. It will likely be barebone, simply a few recordsdata to check our customized guidelines.

Run the next instructions to arrange the typescript undertaking:

npm init –ytsc — init

These instructions will create bundle.json and tsconfig.json recordsdata for us.

Exchange the tsconfig.json file with the next:

Subsequent, let’s arrange ESLint for our undertaking.

Set up ESLint in your undertaking with the next command:

npm set up eslint — save-dev

Subsequent, arrange ESLint for the undertaking with the next command:

npm init @eslint/config

Comply with the immediate and reply the questions just like the illustration beneath:

Our eslintrc.js file ought to seem like the one beneath:

Now our undertaking is totally arrange, and we will compile any file that we add and lint these recordsdata.

Subsequent, we have to create the script that we’ll be utilizing to lint our recordsdata. We’ll be utilizing the eslint module to do that magic from our node script reasonably than operating the eslint. from our terminal. We’ll be utilizing the glob bundle for getting recordsdata on this script, so we have to set up it. You’ll be able to run the next command to put in it:

npm i glob

We have to set up some sort of definitions additionally. Run the next command to put in it:

npm i -D @sorts/eslint @sorts/node @sorts/glob

Now, we will create a file known as lint_files.ts and insert the next inside it:

This file is fairly straightforward to grasp. Now we have 4 helper capabilities used for altering the color of our console. This manner, we will add data, success, warning, and error logs the place mandatory.

The final operate will get known as when this script is known as. Inside this operate, first, we get all TypeScript and JavaScript recordsdata utilizing the glob module. Subsequent, we filter the recordsdata returned from glob and return solely TypeScript and JavaScript recordsdata as these are the recordsdata we need to lint. Subsequent, we create an eslint object.

In response to the documentation, we move a number of the parameters we want, like extensions, errorOnUnmatchedPattern, and baseConfig, which is the eslintrc.js file (the ESLint configuration). We additionally move one other essential parameter: the rulePaths. This selection tells ESLint to search for that listing and test for any ESLint guidelines outlined in that listing.

We loop by way of all of the recordsdata then name the lintFiles methodology, which does the linting and fixes the problem if it may be fastened. We then loop by way of the end result we received from linting, an array of lint outcomes for every file that was linted. The message property is the error message object for every error in every file. The severity property of the message property could be 1 for warning or 2 for error.

Earlier than operating this script, we have to create the listing that we specified because the rulePaths. Create a folder known as lint_rules in your root undertaking and create any file inside it, then compile your code. In case you run this script, you must see the next:

As we had been anticipating, we shouldn’t have any errors.

This part will give attention to creating our first customized rule, however earlier than we do, we have to perceive how codes are structured. We do that by utilizing AST explorer, Summary Syntax Tree. AST explorer helps clarify the breakdown of our code. Let’s have a look at the breakdown of the code pattern beneath:

We’ll be utilizing the AST explorer web site, proven beneath:

If we level our mouse on any a part of the code, we will transverse the node. Let’s take the printTips operate, as an example.

We are able to entry the printTips operate declaration utilizing the FunctionDeclaration node. We are able to entry properties of the like sort, id, identify and even the dad or mum node utilizing the dad or mum property.

Let’s take one other instance, say we’ve the code snippet beneath:

We are able to entry any of the instances by utilizing the SwitchCase node and checking that the node’s take a look at.worth property is what we would like. As an illustration, if we’re working with the primary case, we will use the SwitchCase node and test that the node.take a look at.worth is similar as hiya.

Now, again to our custom rules. To create a customized rule, we are going to create a file contained in the lint_rules folder that we created earlier. The file identify ought to be the rule identify. The rule that we’ll be creating on this article will disallow naming a operate harmful exterior our undertaking’s harmful listing.

Create a file identify no_dangerous_function.js contained in the lint_rules listing and paste the next inside:

First, we created a helper operate that takes in two parameters, context and node and checks if the file being linted is within the harmful listing in our root undertaking. Whether it is on this listing, we simply exit the operate, but when the file isn’t within the harmful listing, we report an error that takes some choices. First is the node which is the node that has the error, the second is the message which will probably be displayed because the linting message, and repair is the operate that can be utilized to repair it and is optionally available.

We additionally exported an object that’s handed to ESLint’s meta describes the metadata of the rule. If you would like the rule to be fixable by ESLint, it is advisable to move a fixable property to the meta, and it could actually both be code or whitespace.

The create property is a operate that takes within the context object, and right here is the place we do the precise work. Now we have three sorts of nodes inside:

  1. CallExpression: This node checks when a operate is known as
  2. FunctionDeclaration: This node checks when a operate is said utilizing the operate key phrase.
  3. ArrowFunctionExpression: This node checks when a operate is said utilizing an arrow operate.

We’d like these three nodes for our use case, as we need to ensure that a operate named harmful is just not known as or declared in any manner exterior the harmful listing.

From the photographs above, we will see why we selected every node, and why we had been in a position to entry or for ArrowFunctionExpression , for FunctionDeclaration, and node.callee.identify for CallExpression. Subsequent, we have to allow this rule, to do that edit the rule property of your eslintrc.js file by including this rule to it.

Add this as one other property of the rule property of your eslintrc.js file:

no_dangerous_function: ‘error’,

Now, all of your recordsdata ought to be supplying you with an error message just like the one beneath:

It’s because the ESLint extension of VSCode can’t discover this rule. We’ll repair that later. Now let’s take a look at our rule. In your app.ts file, add the next:

export operate harmful ()     console.log(‘harmful’)harmful()

In case you lint the recordsdata once more, you must get the next error message. And that is proof that despite the fact that our editor is giving an error message that it could actually’t see the rule, we added it to the eslintrc.js file, and we didn’t get a warning telling us to not identify the operate `harmful` contained in the app.ts file, so our rule is working completely properly.

Let’s create a listing known as harmful and create a file inside it. After that, we will lastly paste the identical code in our app.ts file inside, as you’ll be able to see beneath:

export operate harmful ()     console.log(‘harmful’)harmful()

If we lint our file code once more, solely the app.ts file ought to elevate an error.

Let’s create one other file within the root listing of our undertaking to check for arrow capabilities by making a operate named harmful inside this file.

To repair the warning “Definition for rule ‘no_dangerous_function’ was not discovered. eslint(no_dangerous_function),” we have to inform VSCode to test for customized guidelines in a selected listing. To do that, we have to create VSCode settings for our undertaking. That is executed by making a settings.json file inside our undertaking’s .vscode listing. Paste the next inside this file:

// Place your settings on this file to overwrite default and person settings.    “eslint.choices”:         “rulePaths”: [“lint_rules”],    

All these errors ought to go away, and VSCode can be good sufficient to warn us earlier than linting our recordsdata.

If we hover on this error and click on on the repair button, we will solely disable the rule. However this isn’t sufficient. We’d need to make ESlint repair these points for us routinely for some guidelines.

For instance, for this rule, we will resolve that we need to routinely change the operate identify to notDangerous or one thing else if the repair possibility of ESLint is true or after we click on on the Fast repair button.

Now we have the repair methodology in our commented out, uncomment this methodology, and now click on on the Fast repair possibility ought to give us extra attention-grabbing skills. Additionally, after we lint, the recordsdata get routinely fastened as we’ve set repair as true.

If we click on the button, the operate identify will change to notDangerous. Let’s lint our recordsdata once more, however all our errors will probably be fastened routinely.

And in the event you test your supply code, the harmful operate ought to have modified to notDangerous.

This text has labored you thru establishing and utilizing ESLint with typescript, utilizing the ESLint module reasonably than the CLI instrument, and creating your personal customized ESLint guidelines in your initiatives.

You’ll be able to create extra guidelines to implement kinds that you really want you and the builders working with you to observe utilizing the concept behind this primary rule.

You’ll be able to test the supply code for this text on Github or attain out to me on Twitter.

More Posts