rmorse / babel-plugin-jsx-template-vars

A Babel transform for rendering a template version of your React / Preact app. Useful for generating a pre-render for SSR.
MIT License
10 stars 0 forks source link

Template vars definition #14

Open luisherranz opened 2 years ago

luisherranz commented 2 years ago

Hey Ross, I wonder if you've already thought about using a more idiomatic way to differentiate the template vars from the regular vars.

For example, all variables starting with $.

const Person = ({ name, favoriteColor }) => {
  return (
    <>
      <h1>{name}</h1>
      <p>Favorite color: {favoriteColor}</p>
    </>
  );
};
Person.templateVars = ["name"];
const Person = ({ favoriteColor }) => {
  return (
    <>
      <h1>{$name}</h1>
      <p>Favorite color: {favoriteColor}</p>
    </>
  );
};
rmorse commented 2 years ago

Ahh no I hadn't thought of it that way, but it does sound like a great approach.

I think it would need to tie in with this work.

As it stands, we need to configure things, but #8 is totally achievable imo (with a good amount of work).

Now I've implemented this quite deeply into my application, I am feeling the itch to add aliasing too, so a variable can be exposed as a different name.. but I guess we could still allow for additional configuration, just, not require it, and instead signify template vars in a way like you mention...

As zero config I like the the prefix approach alot!

luisherranz commented 2 years ago

add aliasing too, so a variable can be exposed as a different name

That's a good point 🙂


What about a kind of a magic global object? After all, that's what you need to provide on the other side.

I know the compiler doesn't support dot notation yet, but it could be something like this:

const Person = ({ favoriteColor }) => {
  return (
    <>
      <h1>{$data.name}</h1>
      <p>Favorite color: {favoriteColor}</p>
    </>
  );
};

And even include namespaces to avoid name collision:

const Person = ({ favoriteColor }) => {
  return (
    <>
      <h1>{$data.person.name}</h1>
      <p>Favorite color: {favoriteColor}</p>
    </>
  );
};

This magic global could be typable to avoid typos.

declare global {
  const $data: {
    person: {
      name: string;
    };
  };
}

Anyway, just thinking out loud here 😄