Use arbitrary selectors to search for lines of code (query)
August 28, 2025 ยท View on GitHub
Reports any code found matching an AST expression.
Comparison to ESLint no-restricted-syntax rule
While ESLint has a similar rule, this rule differs in that:
- You can see the actual syntax in the output if you wish (optionally slicing this output with start and/or end); this makes it ideal for querying data rather than just knowing that some syntax is present in such-and-such a file at such-and-such a line number.
- This plugin name suggests it can be used to find items rather than just restrict them (though when used in linting, it indeed serves the purpose of restriction).
- You can use arbitrary JavaScript in your template syntax
Comparison to esquery tool
esquery (demo), a tool used within ESLint, allows queries by AST selector. Here is why we make a separate tool:
- Be able to use from the command line
- Ability to see the output stringified
- Apply to linting if desired as well as querying
Rule Details
This rule aims to allow you to find and display code by AST.
Examples of incorrect code for this rule:
For:
/**
* Over the queried number of arguments.
* @param {string} b
* @param {string} c
*/
export function a (b, c) {
return b + c;
}
export default {
// ...
rules: {
'query/query': ['error', {
defaultFormat: 'string',
queries: {
'FunctionDeclaration[params.length>1]': {
template: 'Oops, too long: `${result}`.'
}
}
}]
}
};
Examples of correct code for this rule:
For:
/**
* Safely under the queried number of arguments.
* @param {string} b
* @param {string} c
*/
export function a (b, c) {
return b + c;
}
export default {
// ...
rules: {
'query/query': ['error', {
queries: {
'FunctionDeclaration[params.length>3]': {
template: 'Oops, too long: ${result}.'
}
}
}]
}
};
Options
Requires a single options object, with:
- a
queriesobject:- Its key should be a string representing the selector.
- Its value should be an object with the following optional properties:
template- A string in the form of an ES6 template (see es6-template-strings). If not present, theresultwill be used instead. If present, it will be passed the following: -result- The selector-identified node represented as a string (i.e., the lines of code pointed to by the selector)start- An integer at which to begin slicing out of the selected lines of code. May be negative as withslice.end- An integer at which to end slicing out of the selected lines of code. May be negative as withslice.format- May override anydefaultFormat(see below).parent- Ifformatis "node", setting this totruewill also show theparentproperties on the AST. Defaults tofalse.
- an optional
defaultFormatstring ("string"(the default) or"node"). Ifnodeis chosen will be represented as stringified Node AST rather than the string found in source.
When Not To Use It
The ESLint rule no-restricted-syntax may be sufficient if you don't need to
display the code.