疏影横斜

疏影横斜

有趣有盼,无灾无难.
github
telegram
misskey

Build my first custom ESLint rule

When I study React, Vue, or use JavaScript and TypeScript more generally, I often use ESLint for linting.
Although I am very familiar with how to use and configure this tool, it wasn't until recently that I truly started writing custom ESLint rules from scratch, during which I learned a lot.
That's what this article is about: how I built custom rules, how I learned about the "abstract syntax tree," and some practical tips and advice.

ESLint#

ESLint is a popular JavaScript code checking tool that helps developers improve code quality and consistency.
The power of ESLint lies in its support for custom rules, allowing developers to ensure that their code adheres to specific standards and conventions.

Preparation#

Before you start building custom rules, you need to make sure that you have ESLint installed in your development environment and that you are familiar with how to use it in your projects.

Additionally, you need to understand how ESLint works and its rule structure. ESLint parses the code, builds an abstract syntax tree (AST), and applies rules to the AST for code checking.
Each rule is a JavaScript function that takes an AST node as a parameter and checks whether the node complies with the rule.

Writing Rules#

To write custom rules, you need to create a JavaScript file and export a rule object.
The rule object contains one or more rule definitions, each of which is a JavaScript function.

Here is a simple rule definition example that checks if variable names adhere to the camelCase naming convention:

module.exports = {
  rules: {
    camelcase: {
      meta: {
        docs: {
          description: 'Enforce camel case naming convention',
          category: 'Stylistic Issues',
          recommended: true,
        },
        schema: [],
        messages: {
          camelcase: "'{{name}}' must be in camel case",
        },
      },
      create(context) {
        function checkVariable(node) {
          const name = node.name;
          if (!/^[a-z][a-zA-Z0-9]*$/.test(name)) {
            context.report({
              node,
              messageId: 'camelcase',
              data: {
                name,
              },
            });
          }
        }
        return {
          Identifier: checkVariable,
        };
      },
    },
  },
};

In the above code, module.exports exports a rule object that contains the camelcase rule. The rule object has two properties:

  • meta: Contains metadata about the rule, such as the rule name, description, category, etc.
  • create: A function that takes a context object as a parameter. The context object contains information related to the current file, such as the AST, parser options, etc. The function returns an object that contains one or more node types and their associated check functions.
    In the checkVariable function, we first get the name of the node and use a regular expression to check if the name adheres to the camelCase naming convention. If the name doesn't comply with the convention, we call context.report to report an error and provide information about the error.

Using Rules#

To use custom rules, you need to add them to your ESLint configuration file (.eslintrc.js > .eslintrc.yaml > .eslintrc.yml > .eslintrc.json > .eslintrc > package.json).
Specifically, you need to import the rule file as a plugin and add the rule name to the rules property. Here is an example configuration file:

module.exports = {
  plugins: ['my-plugin'],
  rules: {
    'my-plugin/camelcase': 'error',
  },
};

In the above configuration file, we import a plugin named my-plugin using the plugins property and add the camelcase rule to the rules property.
We set the severity of the rule to 'error', which means any code that doesn't comply with the rule will be reported as an error.

Debugging Rules#

When developing custom rules, you may need to debug them to find issues. Here are some common debugging techniques:

Use console.log or debugger statements in your rule code to output debug information or pause program execution.
Use the --debug command-line option of ESLint to print detailed debug information.
Use a debugger in your editor, such as VS Code, to set breakpoints in your rule code and step through the code.

Summary#

Custom ESLint rules can help ensure that your code adheres to specific standards and conventions. While this article provides only a simple rule example, you can use more complex rules to check for various issues in your code. For example, you can check for code style, error handling, performance issues, etc. By using custom rules, you can ensure that your code always follows best practices and standards, improving code quality and maintainability.

References#

ESLint
Configuring ESLint

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.