Learn the concept
Custom ESLint Rules & Plugins
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.
Custom Rule Structure:
AST Visitors:
Plugin Structure:
Tools:
// 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'
);
},
});
}
},
};
},
};Developing custom ESLint rules to prevent anti-patterns, enforce internal conventions (e.g., specific module import paths, naming conventions for services), or ensure compliance with security policies, improving code quality and maintainability.
Creating custom autofixable ESLint rules that not only report violations but also automatically correct them, enabling developers to quickly conform to established standards without manual intervention.
Building an ESLint plugin that understands the syntax and semantics of the custom DSL/framework, providing intelligent linting, autocomplete suggestions, and error checking tailored to its specific rules.
Create a custom ESLint rule that disallows `console.log` statements in production code, with an option to allow specific console methods (e.g., `console.warn`, `console.error`).
Develop an ESLint rule that enforces a specific naming convention for custom React hooks (e.g., `use[Name]`), ensuring consistency across a React project.
Meta maintains an extensive suite of internal ESLint rules and plugins to enforce coding standards, optimize performance, and ensure the stability of its massive React and JavaScript applications. These rules often codify best practices derived from years of large-scale development.
Shopify's frontend development teams utilize custom ESLint rules to enforce conventions specific to their Polaris design system and internal framework usage, promoting consistency and reducing cognitive overhead for developers working on various Shopify applications.