10 Steps to Create a Custom ESLint Plugin

devsmitra

Rahul Sharma

Posted on June 28, 2024

10 Steps to Create a Custom ESLint Plugin

Ever get frustrated with confusing or inconsistent function names in your code?

In this article, we're going to solve that problem by creating a custom ESLint plugin to keep code neat and readable by enforcing consistent function names.

So, what's ESLint? Think of it as a helpful tool that checks your code for mistakes and makes sure you're following good coding practices. The cool part? You can create your own rules to fit your style!

Let's get started:

  • New Project: Create a new project and install ESLint by running the following command in your terminal: ```

mkdir myplugin
cd myplugin
npm init --y
npx eslint --init

---
- **Plugin Directory:** Next, create a directory called **eslint-plugin** and a file named **index.js** inside it. This is where our custom rules will live.

---
- **Plugin Structure:** In **index.js**, we'll set up our plugin. This file will have some properties like **meta** and **rules**.

  * **meta:** This holds the plugin name and version.
  * **rules:** This is where we'll define our custom rule to check function names.

```javascript


const plugin = {
  meta: {
    name: "func-prefix-matching",
    version: "0.0.1",
  },
  rules: {}
};


Enter fullscreen mode Exit fullscreen mode

  • Rule Object: Inside rules, we'll create our rule. The key is the rule ID, and the value is an object with a create function.


const plugin = {
  meta: {
    name: "func-prefix-matching",
    version: "0.0.1",
  },
  rules: {
    prefix: {},
  },
};


Enter fullscreen mode Exit fullscreen mode

  • Checking Function Names: create function returns an object with a Identifier method. In the Identifier function, we check if the code is an arrow function. Then, we make sure the function names start with a specific prefix, like "on" or "get" etc.


const rulePrefix = ["is", "pre", "on", "post", "get", "set"];

const isValidName = (name) => {
  const isValid = (prefix) => name.indexOf(prefix) === 0;
  return rulePrefix.some(isValid);
};

const plugin = {
  meta: {
    name: "func-prefix-matching",
    version: "0.0.1",
  },
  rules: {
    prefix: {
      create(context) {
        return {
          Identifier: (node) => {
            if (node.parent?.init?.type === "ArrowFunctionExpression") {
              const { name } = node;
              if (!isValidName(name)) {
                context.report(
                  node,
                  `${name} should start with ${rulePrefix.join(", ")}.`
                );
              }
            }
          },
        };
      },
    },
  },
};




Enter fullscreen mode Exit fullscreen mode

  • Reporting Errors: If a function name doesn't start with the right prefix, we use context.report() to flag it as an error.


context.report(node, `${name} should start with ${rulePrefix.join(", ")}.`);


Enter fullscreen mode Exit fullscreen mode

  • ESLint Configuration: Now, we need to tell ESLint to use our plugin. We do this by adding it to the plugins object in our ESLint configuration file. ```javascript

import prefixMatcher from "./plugin/index.mjs";

export default [
{
files: ["src/*/.js"],
plugins: { prefixMatcher },
},
];

---
- **Configuring the Rule:** Set up the rule in the `rules` section with your chosen namespace.
```javascript


import prefixMatcher from "./plugin/index.mjs";

export default [
  {
    files: ["src/**/*.js"],
    plugins: { prefixMatcher },
    rules: {
      "prefixMatcher/prefix": "warn",
    },
  },
];



Enter fullscreen mode Exit fullscreen mode

  • Testing Code: Create some code examples with both correct and incorrect function names in a folder called src. ```javascript

const someFunction = () => {
console.log("Hello World");
};
someFunction();

---
- **Running ESLint:** Finally, run `npm run lint` in your terminal to see ESLint in action.
```shell


npm run lint


Enter fullscreen mode Exit fullscreen mode

If everything's set up correctly, ESLint will check your code and show error messages for any function names that don't follow the rules.



1:7  warning  someFunction should start with is, pre, on, post, get, set  prefixMatcher/prefix

✖ 1 problem (0 errors, 1 warning)


Enter fullscreen mode Exit fullscreen mode

Thanks for reading! I hope this article helps you create your own ESLint plugin to enforce consistent function names in your code. I'm also attaching the code for the plugin here.


Must Read If you haven't

More content at Dev.to.
Catch me on

Youtube Github LinkedIn Medium Stackblitz Hashnode HackerNoon

💖 💪 🙅 🚩
devsmitra
Rahul Sharma

Posted on June 28, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related