What is AST when writing a plugin, and how do you work with it?
AST (Abstract Syntax Tree) is a tree-like representation of source code, in which every construct of the program (variable, function, statement, expression) is represented as a tree node with a description of its type and properties. During analysis, ESLint does not work with strings of code directly, it first converts the code into an AST, and the plugin then interacts with that tree.
Why AST is needed when writing ESLint rules
When you create a rule, you need to catch a specific piece of code, for example:
- a function call,
- a variable declaration,
- the use of an identifier,
if,return,console.log, a JSX element, and so on.
AST makes this possible, because each of these elements is a node with a type, and ESLint lets you "subscribe" to such nodes while traversing the tree.
What a rule's work with AST looks like (conceptually)
- ESLint parses the code → builds an AST.
- Your rule tells ESLint: "when you encounter a node of type
Identifier, call my code". - ESLint calls your callback with information about the node.
- You decide whether to report an error, ignore it, or fix the code.
Example of an AST node (for the variable const x = 10)
VariableDeclarator
├─ id: Identifier (name: "x")
└─ init: Literal (value: 10)This means: the variable x is declared with the value 10.
A basic example of a rule that works with AST
create(context) {
return {
Identifier(node) {
if (node.name === "foo") {
context.report({
node,
message: "Identifier 'foo' is forbidden."
});
}
}
};
}Here:
Identifieris the AST node typenodeis the node object itself (it hasname,loc,parent, and so on)context.report()is how you report an error to ESLint
How to understand AST and write rules faster
To understand the tree and its nodes, it is convenient to use:
| Tool | Task |
|---|---|
| https://astexplorer.net | see the AST of code in real time |
| espree (the ESLint parser's sandbox) | parses JS into an AST |
| the ESTree specification | describes node types |
AstExplorer is the main tool: you write code on the left → get the AST on the right → pick the needed nodes → write the rule.
Workflow for creating a rule with AST
- In AstExplorer, find the needed node by type (for example
CallExpression). - In your ESLint rule, subscribe to this node:
CallExpression(node) { ... }- Analyze the properties (
node.callee,node.arguments,node.name, etc.). - Call
context.reportwhen needed.
Summary
AST is a structured tree of the code, and an ESLint rule works by traversing this tree and reacting to the needed nodes. Working with AST is the foundation for building any custom ESLint rule.
If needed, I can go on to show how to subscribe to more complex nodes, such as CallExpression or JSX, or how to build autofix (fix in context.report). Continue?
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.