clayrisser / react-ast

render abstract syntax trees with react

Home Page:https://clayrisser.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Starting point for AST transformation

rrjanbiah opened this issue · comments

Are there any starter kit or something to play with the generated AST? I'd thought that passing AST JSON through JMESPath will help in quicker code conversion. But, it looks complex than than.

IOW, are there any best practices for the AST transformation or modification?

The best practice would be to use 🐊Putout code transformer for any purpose of programming changing the code, it has plugins, guide and online editor :)!

@coderaiser Thank for sharing this. Looks interesting for many cases. But, beyond the predefined cases, it seems to be difficult. Anyway, will closely check that for https://github.com/rrjanbiah/react2solid

@rrjanbiah just create an issue in 🐊Putout repository with transform you need (before -> after), and I’ll try to help :)

@coderaiser Will closely check and will do. Thanks for being generous!

Hey, sorry for the late response. I have an example in the following place. Hopefully I can create more examples soon. I want to create an example of React class component, React functional component and express endpoint. The main use case for this project is to create compostable code generators for common repetitive patterns.

https://github.com/clayrisser/react-ast/blob/master/example/index.tsx

@clayrisser, that's definitely better then JSON, but how it's better then @babel/template?

import template from "@babel/template";
import generate from "@babel/generator";

const buildRequire = template.ast(`
    class Hello {
        add(a, b) {
            return a + b;
        }
    }
`);

console.log(generate(ast).code); 

@coderaiser it's better because it supports composablity. In other words, you could build multiple templates with this, and then use them together.

For example, you could create a <ClassReactComponent \> template that generates code for a class based react component. You could then use this component in a larger generator. Then, perhaps in the future, you want to switch your generator to use function components. Instead of rebuilding the entire template, you would just swap out <ClassReactComponent \> with <FunctionReactComponent \>.

In other words, you can componentize and abstract the generation of code into tiny parts and use those pieces together in a composable way.

Generating a react component with template.ast() might solve a code generation problem, but it probably can't be reused for other similar problems.

Hope this makes sense. I need to improve the docs to clearly explain this use case. I think it's really powerful.