Generating Handlebars from a React Abstract Syntax

As a proof of concept, I'm trying to generate Handlebars code from a simple React component. For example, I'd like to transform something like this.

import React from 'react';

const HelloWorld = ({ name, items }) => {
  return (
    <h1>
     Hello {name}!
     <ul>
       {items.map((item, i) => (
         <li key={i}> {item} </li>
       ))}
     </ul>
    </h1>
  )
}

export default HelloWorld;

To something like this.

<h1>
 Hello {{ name }}!
 <ul>
  {{#each items}}
    <li key="{{@index}}">{{ this }}</li>
  {{/each}}
 </ul>
</h1>

My original idea was to use babel, typescript or another AST generator to generate an AST and then traverse it building out the handlebars output. Starting with the default export, traversing the nodes and outputting the return JSX Statements into a resultant string. Has anybody seen something similar where a handlebars template is generated programmatically?



Read more here: https://stackoverflow.com/questions/68459247/generating-handlebars-from-a-react-abstract-syntax

Content Attribution

This content was originally published by George Kemp at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: