render abstract syntax trees using react
Please ★ this repo if you found it useful ★ ★ ★
Abstract syntax trees are difficult to work with by nature. This is a react renderer that makes interacting with abstract syntax trees and rendering code a breeze.
React AST is the ultimate meta programming tool that uses react to render abstract syntax trees. It can be used to build powerful unopinionated code generators and babel plugins that are easy to read and can scale without creating a rats nest of unreadable code.
You can read a post I wrote about this project at the link below.
Render Abstract Syntax Trees with React
BitSpur offers premium Node and React development and support services. Get in touch at bitspur.com.
- works with babel ast
- supports typescript
npm install --save react-ast
import React, { FC } from "react";
import {
Export,
Expression,
Function,
Identifier,
Import,
Interface,
JSX,
ReactNode,
Return,
TypeAnnotation,
TypeReference,
Var,
VarKind,
} from "react-ast";
const code = await render(
<>
<Import default="React" imports={["FC"]} from="react" />
<Export>
<Interface name="HelloProps" />
</Export>
<Var kind={VarKind.Const} typeAnnotation="FC<HelloProps>" name="Hello">
<Function
arrow
params={[
<Identifier
typeAnnotation={
<TypeAnnotation>
<TypeReference name="HelloProps" />
</TypeAnnotation>
}
>
props
</Identifier>,
]}
>
<Return>
<JSX />
</Return>
</Function>
</Var>
<Expression properties="Hello.defaultProps">{{}}</Expression>
<Export default>
<Identifier>Hello</Identifier>
</Export>
</>
);
console.log(code);
The rendered code
import React, { FC } from "react";
export interface HelloProps {}
const Hello: FC<HelloProps> = (props: HelloProps) => {
return <></>;
};
Hello.defaultProps = {};
export default Hello;
Sometimes you might want to render the ast instead of rendering the code.
import React from "react";
import { ClassDeclaration, renderAst } from "react-ast";
const ast = renderAst(<Class name="Hello" />);
console.log(ast);
The rendered AST
{ type: 'File',
program:
{ type: 'Program',
body: [ [Object] ],
directives: [],
sourceType: 'script',
interpreter: null },
comments: [],
tokens: [] }
Submit an issue
You can validate the AST at astexplorer.net with the following settings.
Language | ParserSettings | Transform |
---|---|---|
JavaScript |
babylon7 |
babelv7 |
Enabled the following babylon7 plugins
jsx
typescript
asyncGenerators
classProperties
decorators
doExpressions
dynamicImport
functionBind
functionSent
numericSeparator
objectRestSpread
optionalCatchBinding
optionalChaining
Review the guidelines for contributing
Clay Risser © 2019
Review the changelog
- Clay Risser - Author
A ridiculous amount of coffee ☕ ☕ ☕ was consumed in the process of building this project.
Add some fuel if you'd like to keep me going!