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'
);
},
});
}
},
};
},
};