Query TypeScript ASTs with the esquery API!
npm install @chenshengshui/tsqueryTSQuery is a port of the ESQuery API for TypeScript! TSQuery allows you to query a TypeScript AST for patterns of syntax using a CSS style selector system.
``sh`
npm install tsquery --save-dev
Say we want to select all instances of an identifier with name "Animal", e.g. the identifier in the class declaration, and the identifier in the extends declaration.
We would do something like the following:
`ts
import { tsquery } from '@chenshengshui/tsquery';
const typescript =
class Animal {
constructor(public name: string) { }
move(distanceInMeters: number = 0) {
console.log(\\${this.name} moved \${distanceInMeters}m.\);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
;
const ast = tsquery.ast(typescript);
const nodes = tsquery(ast, 'Identifier[name="Animal"]');
console.log(nodes.length); // 2
`
Try running this code in StackBlitz!
The following selectors are supported:
- AST node type: ForStatement (see common node types)*
- wildcard: [attr]
- attribute existence: [attr="foo"]
- attribute value: or [attr=123][attr=/foo.*/]
- attribute regex: [attr!="foo"]
- attribute conditons: , [attr>2], [attr<3], [attr>=2], or [attr<=3][attr.level2="foo"]
- nested attribute: FunctionDeclaration > Identifier.id
- field: :first-child
- First or last child: or :last-child:nth-child(2)
- nth-child (no ax+b support): :nth-last-child(1)
- nth-last-child (no ax+b support): ancestor descendant
- descendant: parent > child
- child: node ~ sibling
- following sibling: node + adjacent
- adjacent sibling: :not(ForStatement)
- negation: :matches([attr] > :first-child, :last-child)
- matches-any: IfStatement:has([name="foo"])
- has: :statement
- class of AST node: , :expression, :declaration, :function, or :pattern
- Identifier - any identifier (name of a function, class, variable, etc)IfStatement
- , ForStatement, WhileStatement, DoStatement - control flowFunctionDeclaration
- , ClassDeclaration, ArrowFunction - declarationsVariableStatement
- - var, const, let.ImportDeclaration
- - any import statementStringLiteral
- - any stringTrueKeyword
- , FalseKeyword, NullKeyword, AnyKeyword - various keywordsCallExpression
- - function callNumericLiteral
- - any numeric constantNoSubstitutionTemplateLiteral
- , TemplateExpression` - template strings and expressions