Skip to content

Instantly share code, notes, and snippets.

@bpierre
Last active April 9, 2021 14:24
Show Gist options
  • Save bpierre/9d861a308dce3beee95be41dd72861bc to your computer and use it in GitHub Desktop.
Save bpierre/9d861a308dce3beee95be41dd72861bc to your computer and use it in GitHub Desktop.
Custom CSS units implemented with @emotion/cache as a stylis plugin
import { CacheProvider } from "@emotion/react"
import createCache from "@emotion/cache"
function cssUnitPlugin(unitInPx = 8, unit = "gu") {
const re = new RegExp("([0-9]+)" + unit, "g")
const convert = (value) => value.replace(re, replacer)
const replacer = (_, value) => `${value * unitInPx}px`
return (element) => {
if (element.type === "decl" && element.value.includes(unit)) {
element.value = convert(element.value)
}
}
}
const cache = createCache({
key: "css",
stylisPlugins: [ cssUnitPlugin(8, "gu") ],
})
export function App({ children }) {
return (
<CacheProvider value={cache}>
// …
</CacheProvider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment