JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstooling
PrevNext
tooling
senior
custom

How do you create custom ESLint rules and plugins?

eslint
plugins
ast
custom-rules
Quick Answer

Create custom ESLint rules by writing AST visitors that detect patterns and report errors. Rules receive context with report() for violations. Package multiple rules as a plugin with rules and recommended configs. Use AST Explorer to understand code structure.

Detailed Explanation

Custom Rule Structure:

  • meta: Rule metadata (docs, schema)
  • create: Returns AST visitors
  • Report violations with context.report()

AST Visitors:

  • Visit specific node types
  • Access node properties
  • Check patterns
  • Report issues

Plugin Structure:

  • rules: Object of rule definitions
  • configs: Shareable configurations
  • processors: For non-JS files

Tools:

  • AST Explorer for analysis
  • @typescript-eslint/utils for TS

Code Examples

Custom ESLint rule
// eslint-plugin-myorg/rules/no-console-log.js
module.exports = {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'Disallow console.log',
      category: 'Best Practices',
      recommended: true,
    },
    fixable: 'code',
    schema: [{
      type: 'object',
      properties: {
        allow: {
          type: 'array',
          items: { type: 'string' }
        }
      }
    }],
    messages: {
      noConsoleLog: 'Unexpected console.log. Use logger instead.',
    },
  },
  
  create(context) {
    const options = context.options[0] || {};
    const allowed = options.allow || [];
    
    return {
      // Visit CallExpression nodes
      CallExpression(node) {
        if (
          node.callee.type === 'MemberExpression' &&
          node.callee.object.name === 'console' &&
          node.callee.property.name === 'log' &&
          !allowed.includes('log')
        ) {
          context.report({
            node,
            messageId: 'noConsoleLog',
            fix(fixer) {
              return fixer.replaceText(
                node.callee,
                'logger.debug'
              );
            },
          });
        }
      },
    };
  },
};

Resources

ESLint - Working with Rules

docs

AST Explorer

docs

Related Questions

What is ESLint and why should you use it?

junior
linting

How does Babel work and how do you configure it?

senior
transpilation
Previous
What is a monorepo and how do you set one up?
Next
How does Babel work and how do you configure it?