-
-
Save JonathanPicques/78cb1b29d8c318e5abedd32b52c26c27 to your computer and use it in GitHub Desktop.
Fresh Emotion plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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