Welcome to the second episode of “What I Learnt Last Week”. In this episode, we will see how to create custom ESLint rules.
First, I assume you have a basic understanding of ESLint and its usage. Also, check the existing rules before creating yours; what you need may already exist.
You can get the source code of this tutorial on GitHub here
Now, let’s get to the meat of the topic.
Just before then, let’s define our problem:
Let’s say several Engineers in your team have a habit of writing code like so:
But this annoys you because it’s hard to tell what ‘f’, ‘s’, ‘x’ and ‘m’ mean just by looking at the instructionFunction().
To prevent this from happening in the future, you can create a custom ESLint rule.
To do this, we will need the eslint-plugin-local-rules package. Let’s add it as a dev dependency like so:
npm i -D eslint-plugin-local-rules
Then create a file called eslint-local-rules.js
at the root of your application
and add the following code.
Let me explain what each part of the preceding code does:
First, we export the configuration object, with key(s) representing our rule(s) and the value(s) as the configuration object of our rule. In this case, we are calling our rule “no-single-word-variable”.
meta: The meta property is used to provide information about our rule.
type: one of “problem”, “suggestion”, or “layout”.
description: this, for lack of a better term, describes our custom rule.
create()
:
This method returns an object with methods — `VariableDeclareator()` in our case — that ESLint calls when traversing the JavaScript’s Abstract Syntax Tree. The `create()` method takes a “context” object as its only argument.context
:
This object contains all the information that rule. For example, the source code being analyzed, the file name, etc. It also contains some important methods that can be called during the lifecycle of the rule. (See full description here.)VariableDeclarator(). This method will be called whenever ESLint encounters a variable declaration. The `node` represents the declared variable. Then we check if the variable name meets the minimum length requirement.
This might look confusing but it’s pretty much the Abstract Syntax Tree representation of the variable declaration.
report() Finally, we call the “report” method which publishes a warning or an error, depending on the configuration.
loc: this describes the location of the error. If “loc” is not provided, “node” should.
message: this is the error message the linter will display.
Right now, this rule does nothing.
To use our new rule, we need to add it to the eslintrc.js file like so:
module.exports = {
...
plugins: ['eslint-plugin-local-rules'],
"rules": {
"local-rules/no-single-word-variable": "error"
}
}
Also, let’s add the script in our package.json file
{
...
"scripts": {
"lint": "eslint src"
},
}
Now, our custom rule should work
And that’s it! 🎉 We have successfully written our own rule using ESLint.