Created
April 22, 2024 18:59
-
-
Save BarishNamazov/52522dd1552bbc28a781d04756ac3a64 to your computer and use it in GitHub Desktop.
Naive UI plugin for Nuxt that adds styles to the head tag. Removes style load lag. Use with caution as it increases rendered HTML size.
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 { setup } from "@css-render/vue3-ssr"; | |
import { defineNuxtPlugin, type NuxtSSRContext } from "#app"; | |
export default defineNuxtPlugin((nuxtApp) => { | |
if (process.server) { | |
const { collect } = setup(nuxtApp.vueApp); | |
const originalRenderMeta = nuxtApp.ssrContext?.renderMeta; | |
nuxtApp.ssrContext = nuxtApp.ssrContext || ({} as NuxtSSRContext); | |
nuxtApp.ssrContext.renderMeta = () => { | |
if (!originalRenderMeta) { | |
return { | |
headTags: collect(), | |
}; | |
} | |
const originalMeta = originalRenderMeta(); | |
if ("then" in originalMeta) { | |
return originalMeta.then((resolvedOriginalMeta: any) => { | |
return { | |
...resolvedOriginalMeta, | |
headTags: resolvedOriginalMeta["headTags"] + collect(), | |
}; | |
}); | |
} else { | |
return { | |
...originalMeta, | |
headTags: originalMeta["headTags"] + collect(), | |
}; | |
} | |
}; | |
nuxtApp.ssrContext.head = nuxtApp.ssrContext.head || ([] as typeof nuxtApp.ssrContext.head); | |
nuxtApp.ssrContext.head.push({ | |
style: () => | |
collect() | |
.split("</style>") | |
.map((block) => { | |
const id = RegExp(/cssr-id="(.+?)"/).exec(block)?.[1]; | |
const style = (RegExp(/>(.*)/s).exec(block)?.[1] ?? "").trim(); | |
return { | |
"cssr-id": id, | |
innerHTML: style, | |
}; | |
}), | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment