glaze icon indicating copy to clipboard operation
glaze copied to clipboard

Babel plugin to transform a custom `sx` prop for any component

Open kripod opened this issue 6 years ago • 4 comments

Motivation

Calling the useStyling hook is verbose, especially for small components, e.g.:

import { useStyling } from 'glaze';

export default function Component() {
  const sx = useStyling();

  return (
    <p
      className={sx({
        px: 4, // Sets padding-left and padding-right to 1rem
        color: 'white',
        bg: 'red', // Sets background to #f8485e
      })}
    >
      Hello, world!
    </p>
  );
}

Basic example

Instead, an API like below could be made possible with code transforms:

export default function Component() {
  return (
    <p
      sx={{
        px: 4, // Sets padding-left and padding-right to 1rem
        color: 'white',
        bg: 'red', // Sets background to #f8485e
      }}
    >
      Hello, world!
    </p>
  );
}

Details

Style composition (#4) should also be made available.

A custom JSX pragma is not required, nor recommended. If someone opts into using the Babel plugin, TypeScript module augmentation should be applied on React elements, extending the list of available props with sx.

kripod avatar Mar 27 '20 22:03 kripod

For auto-importing the useStyling hook, the implementation in https://github.com/emotion-js/emotion/pull/200 can be utilized. After that, every component with an element using the sx prop should start with:

const sx = useStyling();

kripod avatar Mar 30 '20 13:03 kripod

Hey,

I would love to give a shot at this one. I've never written any babel plugin but I guess that's a cool learning opportunity 😊

Since there's an example I can base myself on I hope it's won't be too difficult :)

tatchi avatar Apr 01 '20 06:04 tatchi

@tatchi Thank you for trying! I’ve also never written a Babel plugin before, but this explanation and the preset for emotion’s css prop may help us through the journey.

Let me know if you have any questions!

kripod avatar Apr 01 '20 06:04 kripod

Now only the documentation and type definitions are left. I'm doing both right now 😊

kripod avatar Apr 21 '20 09:04 kripod