Skip to content

Instantly share code, notes, and snippets.

@ValeriaVG
Last active August 21, 2023 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ValeriaVG/fae78394feee2ae44b9c58521a33d3e9 to your computer and use it in GitHub Desktop.
Save ValeriaVG/fae78394feee2ae44b9c58521a33d3e9 to your computer and use it in GitHub Desktop.
Fresh Emotion plugin
import { Plugin, PluginRenderScripts } from "$fresh/server.ts";
import createEmotionServer from '@emotion/server/create-instance'
import { cache } from '@emotion/css'
const { extractCritical } = createEmotionServer(cache)
const main = `data:application/javascript,import hydrate from "${new URL("./main.ts", import.meta.url).href
}";export default function(state) { hydrate(state); }`;
const emotion: Plugin = {
name: "emotion",
entrypoints: { "main": main },
render: (ctx) => {
const res = ctx.render()
const { css, ids } = extractCritical(res.htmlText)
const scripts: PluginRenderScripts[] = []
if (res.requiresHydration) {
scripts.push({ entrypoint: "main", state: ids })
}
return {
scripts,
styles: [
{ cssText: css, id: ids.join('_') }]
}
}
};
export default emotion
{
"imports": {
"$fresh/": "https://deno.land/x/fresh@1.1.2/",
"preact": "https://esm.sh/preact@10.11.0",
"preact/": "https://esm.sh/preact@10.11.0/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.4",
"@preact/signals": "https://esm.sh/*@preact/signals@1.0.3",
"@preact/signals-core": "https://esm.sh/*@preact/signals-core@1.0.1",
"@emotion/css": "https://esm.sh/@emotion/css@11.10.5",
"@emotion/server/create-instance": "https://esm.sh/@emotion/server@11.10.0/create-instance"
}
}
import { hydrate, cache } from '@emotion/css'
export default function (state: string[]) {
let el = document.getElementById(cache.key)
if (!el) {
el = document.createElement('style')
el.id = cache.key
document.head.appendChild(el)
}
el.innerHTML = ''
hydrate(state)
for (const key in cache.inserted) {
const entry = cache.inserted[key]
if (entry !== true) {
el.innerHTML += entry;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment