Goober

A less than 1KB css-in-js alternative with a familiar API

README

goober


🥜 goober, a less than 1KB css-in-js solution.
Backers on Open Collective Sponsors on Open Collective
version status gzip size downloads coverage Slack

🪒 The Great Shave Off Challenge


Can you shave off bytes from goober? Do it and you're gonna get paid! More info here

Motivation


I've always wondered if you could get a working solution for css-in-js with a smaller footprint. While I was working on a side project I wanted to use styled-components, or more accurately the styled pattern. Looking at the JavaScript bundle sizes, I quickly realized that I would have to include 12kB(styled-components) or11kB(emotion) just so I can use thestyled paradigm. So, I embarked on a mission to create a smaller alternative for these well established APIs.

Why the peanuts emoji?


It's a pun on the tagline.

css-in-js at the cost of peanuts!

🥜goober


Talks and Podcasts


React Round Up 👉 https://reactroundup.com/wrangle-your-css-in-js-for-peanuts-using-goober-ft-cristian-bote-rru-177
ReactDay Berlin 2019 👉  https://www.youtube.com/watch?v=k4-AVy3acqk
PodRocket by LogRocket 👉 https://podrocket.logrocket.com/goober
ngParty 👉 https://www.youtube.com/watch?v=XKFvOBDPeB0

Table of contents


-   Usage
-   Examples
-   Tradeoffs
-   SSR
    -   Browser
    -   SSR
-   API
    -   styled
    -   setup
        -   With prefixer
        -   With theme
        -   With forwardProps
    -   css
    -   targets
    -   extractCss
    -   createGlobalStyles
    -   keyframes
    -   shouldForwardProp
    -   Babel Plugin
    -   Babel Macro Plugin
    -   Next.js
    -   Gatsby
    -   Preact CLI Plugin
    -   CSS Prop
-   Features
    -   Sharing Style
    -   Autoprefixer
    -   TypeScript

Usage


The API is inspired by emotion styled function. Meaning, you call it with your tagName, and it returns a vDOM component for that tag. Note, setup needs to be ran before the styled function is used.

  1. ``` js
  2. import { h } from 'preact';
  3. import { styled, setup } from 'goober';

  4. // Should be called here, and just once
  5. setup(h);

  6. const Icon = styled('span')`
  7.     display: flex;
  8.     flex: 1;
  9.     color: red;
  10. `;

  11. const Button = styled('button')`
  12.     background: dodgerblue;
  13.     color: white;
  14.     border: ${Math.random()}px solid white;

  15.     &:focus,
  16.     &:hover {
  17.         padding: 1em;
  18.     }

  19.     .otherClass {
  20.         margin: 0;
  21.     }

  22.     ${Icon} {
  23.         color: black;
  24.     }
  25. `;
  26. ```

Examples


-   Vanilla
-   React
-   Preact
-   Fre

Comparison and tradeoffs


In this section I would like to compare goober, as objectively as I can, with the latest versions of two most well known css-in-js packages: styled-components and emotion.

I've used the following markers to reflect the state of each feature:

-   ✅ Supported
-   🟡 Partially supported
-   🛑 Not supported

Here we go:

FeatureGooberStyledEmotion
-----------------------------------------------------
Base1.2512.67.4
Framework🛑🛑
Render🛑🛑
`css`
`css`
`styled`
`styled.`
`as`
`.withComponent`🛑
`.attrs`🛑🛑
`shouldForwardProp`
`keyframes`
Labels🛑🛑
ClassNames🛑🛑
Global
SSR
Theming
Tagged
Object
Dynamic

Footnotes

-   [1] goober can render in _any_ dom target. Meaning you can use goober to define scoped styles in any context. Really useful for web-components.
-   [2] Supported only via babel-plugin-transform-goober

SSR


You can get the critical CSS for SSR via extractCss. Take a look at this example: CodeSandbox: SSR with Preact and goober and read the full explanation forextractCSS and targets below.

Benchmarks


The results are included inside the build output as well.

Browser


Coming soon!

SSR


The benchmark is testing the following scenario:

  1. ``` js
  2. import styled from '<packageName>';

  3. // Create the dynamic styled component
  4. const Foo = styled('div')((props) => ({
  5.     opacity: props.counter > 0.5 ? 1 : 0,
  6.     '@media (min-width: 1px)': {
  7.         rule: 'all'
  8.     },
  9.     '&:hover': {
  10.         another: 1,
  11.         display: 'space'
  12.     }
  13. }));

  14. // Serialize the component
  15. renderToString(<Foo counter={Math.random()} />);
  16. ```

The results are:

  1. ```
  2. goober x 200,437 ops/sec ±1.93% (87 runs sampled)
  3. styled-components@5.2.1 x 12,650 ops/sec ±9.09% (48 runs sampled)
  4. emotion@11.0.0 x 104,229 ops/sec ±2.06% (88 runs sampled)

  5. Fastest is: goober
  6. ```

API


As you can see, goober supports most of the CSS syntax. If you find any issues, please submit a ticket, or open a PR with a fix.

styled(tagName: String | Function, forwardRef?: Function)


-   @param {String|Function} tagName The name of the DOM element you'd like the styles to be applied to
-   @param {Function} forwardRef Forward ref function. Usually React.forwardRef
-   @returns {Function} Returns the tag template function.

  1. ``` js
  2. import { styled } from 'goober';

  3. const Btn = styled('button')`
  4.     border-radius: 4px;
  5. `;
  6. ```

Different ways of customizing the styles


Tagged templates functions

  1. ``` js
  2. import { styled } from 'goober';

  3. const Btn = styled('button')`
  4.     border-radius: ${(props) => props.size}px;
  5. `;

  6. <Btn size={20} />;
  7. ```

Function that returns a string

  1. ``` js
  2. import { styled } from 'goober';

  3. const Btn = styled('button')(
  4.     (props) => `
  5.   border-radius: ${props.size}px;
  6. `
  7. );

  8. <Btn size={20} />;
  9. ```

JSON/Object

  1. ``` js
  2. import { styled } from 'goober';

  3. const Btn = styled('button')((props) => ({
  4.     borderRadius: props.size + 'px'
  5. }));

  6. <Btn size={20} />;
  7. ```

Arrays

  1. ``` js
  2. import { styled } from 'goober';

  3. const Btn = styled('button')([
  4.     { color: 'tomato' },
  5.     ({ isPrimary }) => ({ background: isPrimary ? 'cyan' : 'gray' })
  6. ]);

  7. <Btn />; // This will render the `Button` with `background: gray;`
  8. <Btn isPrimary />; // This will render the `Button` with `background: cyan;`
  9. ```

Forward ref function

As goober is JSX library agnostic, you need to pass in the forward ref function for the library you are using. Here's how you do it for React.

  1. ``` js
  2. const Title = styled('h1', React.forwardRef)`
  3.     font-weight: bold;
  4.     color: dodgerblue;
  5. `;
  6. ```

setup(pragma: Function, prefixer?: Function, theme?: Function, forwardProps?: Function)


The call to setup() should occur only once. It should be called in the entry file of your project.

Given the fact that react uses createElement for the transformed elements and preact uses h, setup should be called with the proper _pragma_ function. This was added to reduce the bundled size and being able to bundle an esmodule version. At the moment, it's the best tradeoff I can think of.

  1. ``` js
  2. import React from 'react';
  3. import { setup } from 'goober';

  4. setup(React.createElement);
  5. ```

With prefixer


  1. ``` js
  2. import React from 'react';
  3. import { setup } from 'goober';

  4. const customPrefixer = (key, value) => `${key}: ${value};\n`;

  5. setup(React.createElement, customPrefixer);
  6. ```

With theme


  1. ``` js
  2. import React, { createContext, useContext, createElement } from 'react';
  3. import { setup, styled } from 'goober';

  4. const theme = { primary: 'blue' };
  5. const ThemeContext = createContext(theme);
  6. const useTheme = () => useContext(ThemeContext);

  7. setup(createElement, undefined, useTheme);

  8. const ContainerWithTheme = styled('div')`
  9.     color: ${(props) => props.theme.primary};
  10. `;
  11. ```

With forwardProps


The forwardProps function offers a way to achieve the same shouldForwardProps functionality as emotion and styled-components (with transient props) offer. The difference here is that the function receives the whole props and you are in charge of removing the props that should not end up in the DOM.

This is a super useful functionality when paired with theme object, variants, or any other customisation one might need.

  1. ``` js
  2. import React from 'react';
  3. import { setup, styled } from 'goober';

  4. setup(React.createElement, undefined, undefined, (props) => {
  5.     for (let prop in props) {
  6.         // Or any other conditions.
  7.         // This could also check if this is a dev build and not remove the props
  8.         if (prop === 'size') {
  9.             delete props[prop];
  10.         }
  11.     }
  12. });
  13. ```

The functionality of "transient props" (with a "\$" prefix) can be implemented as follows:

  1. ``` js
  2. import React from 'react';
  3. import { setup, styled } from 'goober';

  4. setup(React.createElement, undefined, undefined, (props) => {
  5.     for (let prop in props) {
  6.         if (prop[0] === '$') {
  7.             delete props[prop];
  8.         }
  9.     }
  10. });
  11. ```

Alternatively you can use goober/should-forward-prop addon to pass only the filter function and not have to deal with the full props object.

  1. ``` js
  2. import React from 'react';
  3. import { setup, styled } from 'goober';
  4. import { shouldForwardProp } from 'goober/should-forward-prop';

  5. setup(
  6.     React.createElement,
  7.     undefined,
  8.     undefined,
  9.     // This package accepts a `filter` function. If you return false that prop
  10.     // won't be included in the forwarded props.
  11.     shouldForwardProp((prop) => {
  12.         return prop !== 'size';
  13.     })
  14. );
  15. ```

css(taggedTemplate)


-   @returns {String} Returns the className.

To create a className, you need to call css with your style rules in a tagged template.

  1. ``` js
  2. import { css } from "goober";

  3. const BtnClassName = css`
  4.   border-radius: 4px;
  5. `;

  6. // vanilla JS
  7. const btn = document.querySelector("#btn");
  8. // BtnClassName === 'g016232'
  9. btn.classList.add(BtnClassName);

  10. // JSX
  11. // BtnClassName === 'g016232'
  12. const App => <button className={BtnClassName}>click</button>
  13. ```

Different ways of customizing css


Passing props to css tagged templates

  1. ``` js
  2. import { css } from 'goober';

  3. // JSX
  4. const CustomButton = (props) => (
  5.     <button
  6.         className={css`
  7.             border-radius: ${props.size}px;
  8.         `}
  9.     >
  10.         click
  11.     </button>
  12. );
  13. ```

Using css with JSON/Object

  1. ``` js
  2. import { css } from 'goober';
  3. const BtnClassName = (props) =>
  4.     css({
  5.         background: props.color,
  6.         borderRadius: props.radius + 'px'
  7.     });
  8. ```

Notice: using css with object can reduce your bundle size.

We can also declare styles at the top of the file by wrapping css into a function that we call to get the className.

  1. ``` js
  2. import { css } from 'goober';

  3. const BtnClassName = (props) => css`
  4.     border-radius: ${props.size}px;
  5. `;

  6. // vanilla JS
  7. // BtnClassName({size:20}) -> g016360
  8. const btn = document.querySelector('#btn');
  9. btn.classList.add(BtnClassName({ size: 20 }));

  10. // JSX
  11. // BtnClassName({size:20}) -> g016360
  12. const App = () => <button className={BtnClassName({ size: 20 })}>click</button>;
  13. ```

The difference between calling css directly and wrapping into a function is the timing of its execution. The former is when the component(file) is imported, the latter is when it is actually rendered.

If you use extractCSS for SSR, you may prefer to use the latter, or the styled API to avoid inconsistent results.

targets


By default, goober will append a style tag to the `` of a document. You might want to target a different node, for instance, when you want to use goober with web components (so you'd want it to append style tags to individual shadowRoots). For this purpose, you can `.bind` a new target to the `styled` and `css` methods:

  1. ``` js
  2. import * as goober from 'goober';
  3. const target = document.getElementById('target');
  4. const css = goober.css.bind({ target: target });
  5. const styled = goober.styled.bind({ target: target });
  6. ```

If you don't provide a target, goober always defaults to `` and in environments without a DOM (think certain SSR solutions), it will just use a plain string cache to store generated styles which you can extract with `extractCSS`(see below).

extractCss(target?)


-   @returns {String}

Returns the `