shawnbot/meta-template

React support

開放

#18 建立於 2017年4月6日

 (0 則留言) (0 個反應) (0 位負責人)JavaScript (9 個分叉)github user discovery
help wantedidea

倉庫指標

星標
 (53 顆星)
PR 合併指標
 (30 天內沒有已合併 PR)

描述

React support would be really interesting. I'm not sure what the JSX AST looks like, but with a little clever pattern matching I think this could be doable. Here are some potential stumbling blocks off the top of my head:

  • AFAIK, React components must return a single element. So we'd either need to enforce that relationship strictly, or detect (with an HTML parser? ugh) whether a template contains more than one top-level element and wrap in a <div></div> accordingly.

  • You can't arbitrarily wrap attributes or open and close tags in conditionals in JSX; dynamic attributes must be set with attr={value}, and conditional nesting is more complicated.

  • Conditional attributes in particular would require detecting patterns like attr="{{ value }}", class="static {{ dynamic }}", or class="{% if x }}x{% else %}y{% endif %}" and transforming to JSX-compatible expressions (attr={value}, class={`static ${dynamic}`}, and class={x ? `x` : `y`}, respectively).

  • Mapping from template variables to props might be tricky. This looks like a pretty straightforward transformation from:

    <ul>
      {% for link in links %}
      <li><a href="{{ link.href }}">{{ link.text }}</a></li>
      {% endfor %}
    </ul>
    

    to:

    export ({links}) => {
      return (
        <ul>
        {links.map(link => {
          return <li><a href={link.href}>{link.text}</a></li>;
        })}
        </ul>
      );
    };
    

    But does the component necessarily get {links: links}, or the links array as props? Do we have to detect all of the "top-level" template variables so that we can generate the right destructuring expression?

One nice thing, at least, is that we wouldn't have to worry about whitespace and could just pipe the generated code through prettier. ✨

貢獻者指南