Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork127
🥜 goober, a less than 1KB 🎉 css-in-js alternative with a familiar API
License
cristianbote/goober
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
🥜 goober, a less than 1KB css-in-js solution.
Can you shave off bytes from goober? Do it and you're gonna get paid!More info here
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 thestyled pattern. Looking at the JavaScript bundle sizes, I quickly realized that I would have to include ~12kB(styled-components) or ~11kB(emotion) just so I can use thestyled paradigm. So, I embarked on a mission to create a smaller alternative for these well established APIs.
It's a pun on the tagline.
css-in-js at the cost of peanuts!🥜goober
- 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 byLogRocket 👉https://podrocket.logrocket.com/goober
- ngParty 👉https://www.youtube.com/watch?v=XKFvOBDPeB0
The API is inspired by emotionstyled function. Meaning, you call it with yourtagName, and it returns a vDOM component for that tag. Note,setup needs to be ran before thestyled function is used.
import{h}from'preact';import{styled,setup}from'goober';// Should be called here, and just oncesetup(h);constIcon=styled('span')` display: flex; flex: 1; color: red;`;constButton=styled('button')` background: dodgerblue; color: white; border:${Math.random()}px solid white; &:focus, &:hover { padding: 1em; } .otherClass { margin: 0; }${Icon} { color: black; }`;
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:
| Feature name | Goober | Styled Components | Emotion |
|---|---|---|---|
| Base bundle size | 1.25 kB | 12.6 kB | 7.4 kB |
| Framework agnostic | ✅ | 🛑 | 🛑 |
| Render with target *1 | ✅ | 🛑 | 🛑 |
css api | ✅ | ✅ | ✅ |
css prop | ✅ | ✅ | ✅ |
styled | ✅ | ✅ | ✅ |
styled.<tag> | ✅ *2 | ✅ | ✅ |
| default export | 🛑 | ✅ | ✅ |
as | ✅ | ✅ | ✅ |
.withComponent | 🛑 | ✅ | ✅ |
.attrs | 🛑 | ✅ | 🛑 |
shouldForwardProp | ✅ | ✅ | ✅ |
keyframes | ✅ | ✅ | ✅ |
| Labels | 🛑 | 🛑 | ✅ |
| ClassNames | 🛑 | 🛑 | ✅ |
| Global styles | ✅ | ✅ | ✅ |
| SSR | ✅ | ✅ | ✅ |
| Theming | ✅ | ✅ | ✅ |
| Tagged Templates | ✅ | ✅ | ✅ |
| Object styles | ✅ | ✅ | ✅ |
| Dynamic styles | ✅ | ✅ | ✅ |
Footnotes
- [1]
goobercan render inany dom target. Meaning you can usegooberto define scoped styles in any context. Really useful for web-components. - [2] Supported only via
babel-plugin-transform-goober
You can get the critical CSS for SSR viaextractCss. Take a look at this example:CodeSandbox: SSR with Preact and goober and read the full explanation forextractCSS andtargets below.
The results are included inside the build output as well.
Coming soon!
The benchmark is testing the following scenario:
importstyledfrom'<packageName>';// Create the dynamic styled componentconstFoo=styled('div')((props)=>({opacity:props.counter>0.5 ?1 :0,'@media (min-width: 1px)':{rule:'all'},'&:hover':{another:1,display:'space'}}));// Serialize the componentrenderToString(<Foocounter={Math.random()}/>);
The results are:
goober x 200,437 ops/sec ±1.93% (87 runs sampled)styled-components@5.2.1 x 12,650 ops/sec ±9.09% (48 runs sampled)emotion@11.0.0 x 104,229 ops/sec ±2.06% (88 runs sampled)Fastest is: gooberAs 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.
@param {String|Function} tagNameThe name of the DOM element you'd like the styles to be applied to@param {Function} forwardRefForward ref function. UsuallyReact.forwardRef@returns {Function}Returns the tag template function.
import{styled}from'goober';constBtn=styled('button')` border-radius: 4px;`;
import{styled}from'goober';constBtn=styled('button')` border-radius:${(props)=>props.size}px;`;<Btnsize={20}/>;
import{styled}from'goober';constBtn=styled('button')((props)=>` border-radius:${props.size}px;`);<Btnsize={20}/>;
import{styled}from'goober';constBtn=styled('button')((props)=>({borderRadius:props.size+'px'}));<Btnsize={20}/>;
import{styled}from'goober';constBtn=styled('button')([{color:'tomato'},({ isPrimary})=>({background:isPrimary ?'cyan' :'gray'})]);<Btn/>;// This will render the `Button` with `background: gray;`<BtnisPrimary/>;// This will render the `Button` with `background: cyan;`
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.
constTitle=styled('h1',React.forwardRef)` font-weight: bold; color: dodgerblue;`;
The call tosetup() should occur only once. It should be called in the entry file of your project.
Given the fact thatreact usescreateElement for the transformed elements andpreact usesh,setup should be called with the properpragma 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.
importReactfrom'react';import{setup}from'goober';setup(React.createElement);
importReactfrom'react';import{setup}from'goober';constcustomPrefixer=(key,value)=>`${key}:${value};\n`;setup(React.createElement,customPrefixer);
importReact,{createContext,useContext,createElement}from'react';import{setup,styled}from'goober';consttheme={primary:'blue'};constThemeContext=createContext(theme);constuseTheme=()=>useContext(ThemeContext);setup(createElement,undefined,useTheme);constContainerWithTheme=styled('div')` color:${(props)=>props.theme.primary};`;
TheforwardProps function offers a way to achieve the sameshouldForwardProps 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.
importReactfrom'react';import{setup,styled}from'goober';setup(React.createElement,undefined,undefined,(props)=>{for(letpropinprops){// Or any other conditions.// This could also check if this is a dev build and not remove the propsif(prop==='size'){deleteprops[prop];}}});
The functionality of "transient props" (with a "$" prefix) can be implemented as follows:
importReactfrom'react';import{setup,styled}from'goober';setup(React.createElement,undefined,undefined,(props)=>{for(letpropinprops){if(prop[0]==='$'){deleteprops[prop];}}});
Alternatively you can usegoober/should-forward-prop addon to pass only the filter function and not have to deal with the fullprops object.
importReactfrom'react';import{setup,styled}from'goober';import{shouldForwardProp}from'goober/should-forward-prop';setup(React.createElement,undefined,undefined,// This package accepts a `filter` function. If you return false that prop// won't be included in the forwarded props.shouldForwardProp((prop)=>{returnprop!=='size';}));
@returns {String}Returns the className.
To create a className, you need to callcss with your style rules in a tagged template.
import{css}from"goober";constBtnClassName=css`border-radius:4px;`;// vanilla JSconstbtn=document.querySelector("#btn");// BtnClassName === 'g016232'btn.classList.add(BtnClassName);// JSX// BtnClassName === 'g016232'constApp=><buttonclassName={BtnClassName}>click</button>
import{css}from'goober';// JSXconstCustomButton=(props)=>(<buttonclassName={css`border-radius:${props.size}px; `}> click</button>);
import{css}from'goober';constBtnClassName=(props)=>css({background:props.color,borderRadius:props.radius+'px'});
Notice: usingcss with object can reduce your bundle size.
We can also declare styles at the top of the file by wrappingcss into a function that we call to get the className.
import{css}from'goober';constBtnClassName=(props)=>css`border-radius:${props.size}px;`;// vanilla JS// BtnClassName({size:20}) -> g016360constbtn=document.querySelector('#btn');btn.classList.add(BtnClassName({size:20}));// JSX// BtnClassName({size:20}) -> g016360constApp=()=><buttonclassName={BtnClassName({size:20})}>click</button>;
The difference between callingcss 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 useextractCSS for SSR, you may prefer to use the latter, or thestyled API to avoid inconsistent results.
By default, goober will append a style tag to the<head> 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 thestyled andcss methods:
import*asgooberfrom'goober';consttarget=document.getElementById('target');constcss=goober.css.bind({target:target});conststyled=goober.styled.bind({target:target});
If you don't provide a target, goober always defaults to<head> 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 withextractCSS(see below).
@returns {String}
Returns the<style> tag that is rendered in a target and clears the style sheet. Defaults to<head>.
const{ extractCss}=require('goober');// After your app has rendered, just call it:conststyleTag=`<style>${extractCss()}</style>`;// Note: To be able to `hydrate` the styles you should use the proper `id` so `goober` can pick it up and use it as the target from now on
To define your global styles you need to create aGlobalStyles component and use it as part of your tree. ThecreateGlobalStyles is available atgoober/global addon.
import{createGlobalStyles}from'goober/global';constGlobalStyles=createGlobalStyles` html, body { background: light; } * { box-sizing: border-box; }`;exportdefaultfunctionApp(){return(<divid="root"><GlobalStyles/><Navigation><RestOfYourApp></div> )}
Before the global addon,goober/global, there was a method namedglob that was part of the main package that would do the same thing, more or less. Having only that method to define global styles usually led to missing global styles from the extracted css, since the pattern did not enforce the evaluation of the styles at render time. Theglob method is still exported fromgoober/global, in case you have a hard dependency on it. It still has the same API:
import{glob}from'goober';glob` html, body { background: light; } * { box-sizing: border-box; }`;
keyframes is a helpful method to define reusable animations that can be decoupled from the main style declaration and shared across components.
import{keyframes}from'goober';constrotate=keyframes` from, to { transform: rotate(0deg); } 50% { transform: rotate(180deg); }`;constWicked=styled('div')` background: tomato; color: white; animation:${rotate} 1s ease-in-out;`;
To implement theshouldForwardProp without the need to provide the full loop overprops you can use thegoober/should-forward-prop addon.
import{h}from'preact';import{setup}from'goober';import{shouldForwardProp}from'goober/should-forward-prop';setup(h,undefined,undefined,shouldForwardProp((prop)=>{// Do NOT forward props that start with `$` symbolreturnprop['0']!=='$';}));
You're in love with thestyled.div syntax? Fear no more! We got you covered with a babel plugin that will take your lovely syntax fromstyled.tag and translate it to goober'sstyled("tag") call.
npm i --save-dev babel-plugin-transform-goober# oryarn add --dev babel-plugin-transform-gooberVisit the package in here for more info (https://github.com/cristianbote/goober/tree/master/packages/babel-plugin-transform-goober)
A babel-plugin-macros macro for [🥜goober][goober], rewritingstyled.div syntax tostyled('div') calls.
Once you've configuredbabel-plugin-macros, change your imports fromgoober togoober/macro.
Now you can create your components usingstyled.* syntax:.
import{styled}from'goober/macro';constButton=styled.button` margin: 0; padding: 1rem; font-size: 1rem; background-color: tomato;`;
Want to usegoober with Next.js? We've got you covered! Follow the example below or from the mainexamples directory.
npx create-next-app --example with-goober with-goober-app# oryarn create next-app --example with-goober with-goober-appWant to usegoober with Gatsby? We've got you covered! We have our own plugin to deal with styling your Gatsby projects.
npm i --save goober gatsby-plugin-goober# oryarn add goober gatsby-plugin-gooberIf you use Goober with Preact CLI, you can usepreact-cli-goober-ssr
npm i --save-dev preact-cli-goober-ssr# oryarn add --dev preact-cli-goober-ssr# preact.config.jsconst gooberPlugin = require('preact-cli-goober-ssr')export default (config, env) => { gooberPlugin(config, env)}
When you build your Preact application, this will runextractCss on your pre-rendered pages and add critical styles for each page.
You can use a customcss prop to pass in styles on HTML elements with this Babel plugin.
Installation:
npm install --save-dev @agney/babel-plugin-goober-css-prop
List the plugin in.babelrc:
{ "plugins": [ "@agney/babel-plugin-goober-css-prop" ]}Usage:
<maincss={` display: flex; min-height: 100vh; justify-content: center; align-items: center; `}><h1css="color: dodgerblue">Goober</h1></main>
- Basic CSS parsing
- Nested rules with pseudo selectors
- Nested styled components
- Extending Styles
- Media queries (@media)
- Keyframes (@keyframes)
- Smart (lazy) client-side hydration
- Styling any component
- via
const Btn = ({className}) => {...}; const TomatoBtn = styled(Btn)`color: tomato;`
- via
- Vanilla (via
cssfunction) globalStyle(viaglob) so one would be able to create global styles- target/extract from elements other than
<head> - vendor prefixing
goober supports Content Security Policy nonces for inline styles. Setwindow.__nonce__ before loading the library:
<scriptnonce="your-nonce-here"> window.__nonce__ = 'your-nonce-here';</script>
The nonce will be added to goober's<style> element.
There are a couple of ways to effectively share/extend styles across components.
You can extend the desired component that needs to be enriched or overwritten with another set of css rules.
import{styled}from'goober';// Let's declare a primitive for our styled componentconstPrimitive=styled('span')` margin: 0; padding: 0;`;// Later on we could get the primitive shared styles and also add our ownsconstContainer=styled(Primitive)` padding: 1em;`;
Another helpful way to extend a certain component is with theas property. Given our example above we could modify it like:
import{styled}from'goober';// Our primitive elementconstPrimitive=styled('span')` margin: 0; padding: 0;`;constContainer=styled('div')` padding: 1em;`;// At composition/render time<Primitiveas={'div'}/>// <div />// Or using the `Container`<Primitiveas={Container}/>// <div />
Autoprefixing is a helpful way to make sure the generated css will work seamlessly on the whole spectrum of browsers. With that in mind, the coregoober package can't hold that logic to determine the autoprefixing needs, so we added a new package that you can choose to address them.
npm install goober# oryarn add gooberAfter the main package is installed it's time to bootstrap goober with it:
import{setup}from'goober';import{prefix}from'goober/prefixer';// Bootstrap goobersetup(React.createElement,prefix);
And voilà! It is done!
goober comes with type definitions build in, making it easy to get started in TypeScript straight away.
If you're using custom props and wish to style based on them, you can do so as follows:
interfaceProps{size:number;}styled('div')<Props>` border-radius:${(props)=>props.size}px;`;// This also works!styled<Props>('div')` border-radius:${(props)=>props.size}px;`;
If you're using acustom theme and want to add types to it, you can create a declaration file at the base of your project.
// goober.d.t.simport'goober';declare module'goober'{exportinterfaceDefaultTheme{colors:{primary:string;};}}
You should now have autocompletion for your theme.
constThemeContainer=styled('div')` background-color:${(props)=>props.theme.colors.primary};`;
goober supports all major browsers (Chrome, Edge, Firefox, Safari).
To support IE 11 and older browsers, make sure to use a tool likeBabel to transform your code into code that works in the browsers you target.
Feel free to try it out and checkout the examples. If you wanna fix something feel free to open a issue or a PR.
Thank you to all our backers! 🙏
Support this project by becoming a sponsor. Your logo will show up here with a link to your website.
About
🥜 goober, a less than 1KB 🎉 css-in-js alternative with a familiar API
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
