Make a Rule (ESLint)

Make a New Rule

A super basic ESLint rule file[1] in Typescript looks like this:

import type { Rule } from "eslint";

const rule = {
    meta: {
        name: "new-rule",
        type: "problem",
        docs: {
            description: "Description of the rule in the rules index.",
            recommended: false,
        },
        messages: {
            newRule:
                "This is what will show in ESLint when the rule is violated.",
        },
    },

    create(context) {
        return {
            JSXElement: (node: Rule.Node) => {
                context.report({
                    node,
                    messageId: "newRule",
                });
            },
        };
    },
};

export default rule;

This will trigger an error at every JSXElement. ESLint traverses the AST[4,5] of the Javascript/Typescript document and runs one of the functions found in the return of the create property when that type is found. Think of them like you would CSS selectors, where you can even use a property name like "JSXElement > JSXElement" to only trigger when there is a JSXElement that is a direct descendant of another JSXElement.

References

  1. Custom Rules - ESLint - Pluggable JavaScript Linter
  2. GitHub - DarkPurple141/eslint-codemod-utils: A collection of AST Utils to mimic jscodeshift esque precision to codemods in eslint
  3. Creating Custom Eslint Rules. How to use Eslint like a pro | by Babatunde Koiki | Better Programming
  4. AST explorer
  5. TypeScript AST Viewer
  6. JSCodeShift

Last modified: 202401040446