Skip to content

how to use esquery with ts-morph? #142

@jon9090

Description

@jon9090

How can I use esquery in conjunction with ts-morph to retrieve nodes from the Abstract Syntax Tree (AST) by query path similar to CSS? For instance, given the query path CallExpression > ObjectLiteralExpression > PropertyAssignment[name="arg1"], how can I retrieve the node of type PropertyAssignment with the name arg1?

Here's an example code I've been trying to use to accomplish this, but it doesn't seem to work:

codesandbox

import "./styles.css";
import esquery from "esquery";
import { Project } from "ts-morph";

const project = new Project();
const sourceFile = project.createSourceFile(
  "foo.ts",
  `
class Foo {
  bar() {
    const result = create({
      arg1: true,
      arg2: false
    });
  }
}
`
);

const fooClass = sourceFile.getClass("Foo");

const matches = esquery(
  fooClass,
  'CallExpression > ObjectLiteralExpression > PropertyAssignment[name="arg1"]'
);

console.log({ matches });

Although I'm aware that ts-morph allows me to parse code into an AST, I'm specifically interested in using esquery to retrieve nodes by query path similar to CSS. Is there a way to combine the two approaches or is there an alternative solution that achieves a similar outcome?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions