0.0.6 • Published 4 years ago

@chenshengshui/tsquery v0.0.6

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

TSQuery

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.

Installation

npm install tsquery --save-dev

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 '@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!

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
0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago