npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@nksaraf/goober

v2.0.0-beta.1

Published

A less than 1KB css-in-js solution

Downloads

7

Readme

🥜 goober, a less than 1KB css-in-js solution.

Backers on Open Collective Sponsors on Open Collective

version status gzip size downloads coverage Slack Greenkeeper badge

Motivation

I always wondered, if you can get a working solution for css-in-js with a smaller footprint. I started a project and wanted a to use styled-components. Looking at their sizes, it seems that I would rather not include ~16kB(styled-components) or ~11kB(emotion) just so I can use the styled paradigm. So, I embarked in a mission to create a smaller alternative for these well established apis.

Table of contents

Usage

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

import { h } from 'preact';
import { styled, setup } from 'goober';

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

const Icon = styled('span')`
    display: flex;
    flex: 1;
    color: red;
`;

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

    &:focus,
    &:hover {
        padding: 1em;
    }

    .otherClass {
        margin: 0;
    }

    ${Icon} {
        color: black;
    }
`;

Examples

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 for extractCSS and targets below.

Benchmarks

You results are included inside the build output as well.

Browser

These are not yet measured. Need some time.

SSR

The benchmark is testing the following scenario:

import styled from 'package';

// Create the dynamic styled component
const Foo = styled('div')(props => ({
    opacity: props.counter > 0.5 ? 1 : 0,
    '@media (min-width: 1px)': {
        rule: 'all'
    },
    '&:hover': {
        another: 1,
        display: 'space'
    }
}));

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

The results are:

goober x 39,348 ops/sec ±1.67% (87 runs sampled)
styled-components x 21,469 ops/sec ±3.60% (85 runs sampled)
emotion x 46,504 ops/sec ±4.67% (85 runs sampled)

Fastest is: emotion

API

As you can see it supports most of the syntaxes of CSS. If you find any issues, please submit a ticket or even a PR with a fix.

styled(tagName)

  • @param {String} tagName The name of the dom element you'd like the styled to be applied to
  • @returns {Function} Returns the tag template function.
import { styled } from 'goober';

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

Different ways of customizing the styles

Tagged templates functions
import { styled } from 'goober';

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

<Btn size={20} />;
Function that returns a string
import { styled } from 'goober';

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

<Btn size={20} />;
JSON/Object
import { styled } from 'goober';

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

<Btn size={20} />;

setup(pragma: Function)

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 esmodule version. At the moment I think it's the best tradeoff we can have.

import React from 'react';
import { setup } from 'goober';

setup(React.createElement);

css(taggedTemplate)

  • @returns {String} Returns the className.

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

import { css } from "goober";

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

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

// JSX
// BtnClassName === 'g016232'
const App => <button className={BtnClassName}>click</button>

Different ways of customizing css

Passing props to css tagged templates
import { css } from 'goober';

// JSX
const CustomButton = props => (
    <button
        className={css`
            border-radius: ${props.size}px;
        `}
    >
        click
    </button>
);

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

import { css } from 'goober';

const BtnClassName = props => css`
    border-radius: ${props.size}px;
`;

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

// JSX
// BtnClassName({size:20}) -> g016360
const App = () => <button className={BtnClassName({ size: 20 })}>click</button>;

targets

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 the styled and css methods:

import * as goober from 'goober';
const target = document.getElementById('target');
const css = goober.css.bind({ target: target });
const styled = 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 with extractCSS(see below).

extractCss(target?)

  • @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:
const styleTag = `<style id="_goober">${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

glob

To create a global style, you need to call glob with your global tagged template. Usually here's a good idea to place document wide styles.

import { glob } from 'goober';

glob`
  html,
  body {
    background: light;
  }

  * {
    box-sizing: border-box;
  }
`;

Integrations

Babel plugin

You're in love with the styled.div syntax? Fear no more! We got you covered with a babel plugin that will take your lovely syntax from styled.tag and translate it to goober's styled("tag") call.

npm i --save-dev babel-plugin-transform-goober
# or
yarn add --dev babel-plugin-transform-goober

Visit the package in here for more info (https://github.com/cristianbote/goober/tree/master/packages/babel-plugin-transform-goober)

Gatsby

Want to use goober with Gatsby? We've got you covered! We have our own plugin to deal with styling your Gatsby projects.

npm i --save gatsby-plugin-goober
# or
yarn add gatsby-plugin-goober

Features

  • [x] Basic CSS parsing
  • [x] Nested rules with pseudo selectors
  • [x] Nested styled components
  • [x] Extending Styles
    • via const TomatoButton = styled(StyledBtn)`color: tomato;`
  • [x] Media queries (@media)
  • [x] Keyframes (@keyframes)
  • [x] Smart(lazy) client-side hydration
  • [x] Styling any component
    • via const Btn = ({className}) => {...}; const TomatoBtn = styled(Btn)`color: tomato;`
  • [x] Vanilla(via css function)
  • [x] globalStyle(via glob) so one would be able to create global styles
  • [x] target/extract from elements other than <head>
  • [ ] Vendor prefixing

Browser support

goober uses microbundle to bundle and transpile it's src into code that browsers can leverage. As you might figure it out, until now, Internet Explorer was the buggiest of them all. goober works on IE9, as we've successfully test it.

IE 9
iOS 9.3
Chrome 42
FF 34
Safari 9

Contributing

Feel free to try it out and checkout the examples. If you wanna fix something feel free to open a issue or a PR.

Backers

Thank you to all our backers! 🙏

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website.