Sub topic 17
Writing a Custom ESLint Rule
Shared configs and plugins cover most needs. Some teams also have conventions that no published rule enforces, such as a banned API, a required wrapper function, or a naming pattern specific to the codebase. ESLint lets you write your own rule for these cases. A rule is a small JavaScript module that inspects the parsed code and reports problems.
This chapter assumes you already have a working eslint.config.js flat config, understand rule severities, and know ES module syntax. You will build a rule that flags console.log calls, test it, and then harden it against the edge cases that trip up first attempts.
How ESLint Runs a Rule
ESLint never matches text with regular expressions. It parses each file into an abstract syntax tree (AST). An AST is a tree of nodes, and each node describes one piece of syntax, such as a function call, an identifier, or a string literal. ESLint uses the ESTree node format.
ESLint walks the tree depth-first. Each rule supplies a create(context) function that returns a visitor, an object whose keys are node types. When the traversal reaches a node of a matching type, ESLint calls your handler with that node. The handler checks the node and calls context.report() if something is wrong.
To see the shape of a node, paste code into an AST viewer such as astexplorer.net and pick the espree parser. The call console.log("hi") produces this structure:
| Node | Type | Key properties |
|---|---|---|
| The whole call | `CallExpression` | `callee`, `arguments` |
| `console.log` | `MemberExpression` | `object`, `property`, `computed` |
| `console` | `Identifier` | `name: "console"` |
| `log` | `Identifier` | `name: "log"` |
The Anatomy of a Rule Module
A rule exports an object with two parts:
metadescribes the rule.typeis"problem","suggestion", or"layout".messagesmaps message IDs to text.schemadescribes the rule's options, and an empty array means the rule takes no options. If the rule can autofix,fixablemust be set.create(context)returns the visitor.contextgives youreport(), the rule'soptions, andsourceCode, which provides access to tokens, comments, and scope information.
Here is a first version that handles the plain case:
// rules/no-console-log.js
export default {
meta: {
type: "suggestion",
docs: { description: "Disallow console.log calls" },
messages: { noLog: "Unexpected console.log." },
schema: [],
},
create(context) {
return {
CallExpression(node) {
const callee = node.callee;
if (
callee.type === "MemberExpression" &&
callee.object.type === "Identifier" &&
callee.object.name === "console" &&
callee.property.type === "Identifier" &&
callee.property.name === "log"
) {
context.report({ node, messageId: "noLog" });
}
},
};
},
};Use messageId rather than an inline message string. It keeps wording in one place, and tests can assert on the ID instead of exact text.
Registering the Rule Through a Local Plugin
Flat config only loads rules through plugins. You don't have to publish one, because a plain object with a rules key is a valid plugin. The prefix you choose (local here) becomes the rule's namespace.
// eslint.config.js (requires "type": "module" in package.json)
import js from "@eslint/js";
import globals from "globals";
import noConsoleLog from "./rules/no-console-log.js";
export default [
js.configs.recommended,
{
files: ["**/*.js"],
languageOptions: {
ecmaVersion: "latest",
sourceType: "module",
globals: { ...globals.node },
},
plugins: {
local: { rules: { "no-console-log": noConsoleLog } },
},
rules: {
"local/no-console-log": "error",
},
},
];Run npx eslint .. Every console.log call now produces an local/no-console-log error. Calls such as console.error pass.
Testing with RuleTester
You need tests for a rule, because a rule that is too loose or too strict fails quietly across the whole codebase. ESLint ships RuleTester, which lints code snippets and checks the reports. When a test runner such as Mocha or Vitest provides global describe and it, RuleTester uses them. Without them, it runs the cases directly and throws on the first failure, so plain node is enough.
// rules/no-console-log.test.js
import { RuleTester } from "eslint";
import rule from "./no-console-log.js";
const ruleTester = new RuleTester({
languageOptions: { ecmaVersion: "latest", sourceType: "module" },
});
ruleTester.run("no-console-log", rule, {
valid: [
"console.error('bad');",
"logger.log('fine');",
"const console = { log() {} }; console.log('shadowed');",
],
invalid: [
{ code: "console.log('x');", errors: [{ messageId: "noLog" }] },
{ code: "console['log']('x');", errors: [{ messageId: "noLog" }] },
{ code: "console?.log('x');", errors: [{ messageId: "noLog" }] },
],
});
console.log("All tests passed.");Run node rules/no-console-log.test.js. The first version fails twice. It misses console['log'], and it wrongly flags the local variable named console. The optional-chaining case already passes. ESLint wraps console?.log('x') in a ChainExpression, but the inner node is still a CallExpression whose callee is a MemberExpression.
Handling Edge Cases
Computed member access
In console['log'], the computed flag is true and property is a Literal node whose value is "log". Check both forms of access.
Shadowed names
A name match does not prove you have the global console. The rule should ask the scope manager, which tracks where every variable is declared. context.sourceCode.getScope(node) returns the innermost scope at that node. Walk up through upper scopes until you find a variable named console. A variable the user declared has one or more defs. A global from languageOptions.globals has none.
// rules/no-console-log.js
function isLogProperty(callee) {
if (!callee.computed) {
return callee.property.type === "Identifier" && callee.property.name === "log";
}
return callee.property.type === "Literal" && callee.property.value === "log";
}
function isShadowed(scope, name) {
for (let s = scope; s; s = s.upper) {
const variable = s.set.get(name);
if (variable) return variable.defs.length > 0;
}
return false;
}
export default {
meta: {
type: "suggestion",
docs: { description: "Disallow console.log calls" },
messages: { noLog: "Unexpected console.log." },
schema: [],
},
create(context) {
return {
CallExpression(node) {
const callee = node.callee;
if (
callee.type !== "MemberExpression" ||
callee.object.type !== "Identifier" ||
callee.object.name !== "console" ||
!isLogProperty(callee)
) {
return;
}
if (isShadowed(context.sourceCode.getScope(node), "console")) return;
context.report({ node, messageId: "noLog" });
},
};
},
};Run the tests again. All six cases pass.
Limits you should accept
Static analysis cannot follow every alias. Code like const { log } = console; log("x") or const c = console; c.log("x") gets past this rule. Covering those cases means tracking references through assignments. That adds a lot of complexity for code that rarely appears. Write down known gaps in the rule's docs instead of chasing every case.
When a Custom Rule Is Worth It
| Situation | Better choice |
|---|---|
| A published rule or plugin already does it | Use the existing rule |
| A simple syntax pattern to ban | `no-restricted-syntax`, `no-restricted-imports`, or `no-restricted-globals` |
| Scope-aware checks, options, or fixes | Custom rule |
| Formatting concerns | Leave formatting to Prettier, not a rule |
A custom rule is code you own. It needs tests, documentation, and updates when ESLint's APIs change. For example, ESLint 9 replaced context.getScope() with context.sourceCode.getScope(node).
Exercise
Your rule's visitor key is CallExpression, but you want to flag new Date() calls with no arguments. Which visitor key should you use, and which node properties do you check?
Show answer
Use NewExpression. Check that node.callee.type is "Identifier", node.callee.name is "Date", and node.arguments.length is 0. To avoid flagging a locally declared Date class, also check the scope with context.sourceCode.getScope(node), as the console rule does.
Exercise
A teammate adds "local/no-console-log": "error" to the rules but leaves out the plugins entry. What happens, and why?
Show answer
ESLint stops with a configuration error saying it cannot find the plugin "local". In flat config, a namespaced rule only resolves when an object in the same config array registers a plugin under that namespace in its plugins key and that object applies to the file.
Exercise
Add a RuleTester case that proves the rule ignores console.log on an object that is not the global console, written without declaring a variable named console.
Show answer
Add a valid case such as "window.console.log('x');". The callee's object is a MemberExpression (window.console), not an Identifier named console, so the rule returns early without reporting. Note that the rule does report the real global through window, which is an accepted gap.