"jQuery for React AST"?

47 views Asked by At

Is there such a thing as a "jQuery for React AST"? That like jQuery allows for elegant search, traversal, creation, mutation of an AST that contains things like JSXNode, etc? I saw that acorn has some basic traversal stuff, but it isn't super usable for repeatedly doing reorders, insertions, wrapping a component in {flag && } to conditionally render, etc, etc. I'm not even sure how to google for this except "jquery for AST" which, uh yeah, didn't work.

1

There are 1 answers

0
coderaiser On

Subsecond

You can use Subsecond for this purpose, here is how it will looks like:

Input:

<h1>hello world</h1>

Output:

<h2>hello world</h2>

Transformation:

S('JSXIdentifier').each((node) => {
  node.text('h2');
})

Here is playground.

Putout

Also there is a way to do similar things using declarative approach with help of Putout I'm working on:

Change tag

Input:

<h1>hello world</h1>

Output:

<h2>hello world</h2>

Transformation:

export const replace = () => ({
    '<h1>__a</h1>': '<h2>__a</h2>',
});

Here is playground.

Change Attribute

You can also change an attribute className to class:

Input:

const div = <div className="abc">{x}</div>

Output:

const div = <div class="abc">{x}</div>

Transformation:

export const replace = () => ({
    '<div className="__a">__jsx_children</div>': '<div class="__a">__jsx_children</div>',
});

Here is playground