Skip to content

wongchichong/tsquery

This branch is 13 commits ahead of, 11 commits behind phenomnomnominal/tsquery:master.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

f44fe49 Â· Jul 6, 2023
Jul 6, 2023
Jul 6, 2023
May 1, 2023
Apr 21, 2018
Apr 22, 2018
May 20, 2018
Apr 22, 2022
Apr 22, 2018
Sep 3, 2018
Apr 17, 2022
Mar 18, 2023
Jul 6, 2023
Jul 6, 2023
Oct 16, 2019
Jun 2, 2018

Repository files navigation

TSQuery

npm version Code Climate Test Coverage

TSQuery 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.

Check out the ESQuery demo - note that the demo requires JavaScript code, not TypeScript

You can also check out the TSQuery Playground - Lovingly crafted by Uri Shaked

Installation

npm install @phenomnomnominal/tsquery --save-dev

Upgrading from version 4.x.x to 5.x.x

  • Update all your calls to tsquery.map() to make sure they match the new contract. For more information, check phenomnomnominal#76.

Examples

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:

import { tsquery } from '@phenomnomnominal/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!

Selectors

The following selectors are supported:

Common AST node types

  • Identifier - any identifier (name of a function, class, variable, etc)
  • IfStatement, ForStatement, WhileStatement, DoStatement - control flow
  • FunctionDeclaration, ClassDeclaration, ArrowFunction - declarations
  • VariableStatement - var, const, let.
  • ImportDeclaration - any import statement
  • StringLiteral - any string
  • TrueKeyword, FalseKeyword, NullKeyword, AnyKeyword - various keywords
  • CallExpression - function call
  • NumericLiteral - any numeric constant
  • NoSubstitutionTemplateLiteral, TemplateExpression - template strings and expressions

About

TypeScript AST query library

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 99.6%
  • JavaScript 0.4%