Last active
January 7, 2021 15:37
-
-
Save emmenko/b9debcf4be523d00ee1eee314896aa5f to your computer and use it in GitHub Desktop.
Patch Emotion SSR for Lobotomized Owl selectors
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 React from 'react'; | |
import { renderToString } from 'react-dom/server'; | |
import createEmotionServer from '@emotion/server/create-instance'; | |
import { CacheProvider } from '@emotion/react'; | |
import { createDocsCache, docsCacheKey } from './utils/create-emotion-cache'; | |
const patchedLobotomizedOwlSelector = '> *:not(style) ~ *:not(style)'; | |
const lobotomizedOwlSelectorRegex = />\s*\*\s*\+\s*\*/g; | |
export const replaceRenderer = ({ | |
bodyComponent, | |
replaceBodyHTMLString, | |
setHeadComponents, | |
}) => { | |
// https://emotion.sh/docs/ssr#on-server | |
// https://emotion.sh/docs/ssr#gatsby | |
const cache = createDocsCache(); | |
const { extractCritical } = createEmotionServer(cache); | |
const { html, css, ids } = extractCritical( | |
renderToString(<CacheProvider value={cache}>{bodyComponent}</CacheProvider>) | |
); | |
const patchedHtml = html.replace(lobotomizedOwlSelectorRegex, patchedLobotomizedOwlSelector); | |
const patchedCss = css.replace(lobotomizedOwlSelectorRegex, patchedLobotomizedOwlSelector); | |
replaceBodyHTMLString(patchedHtml); | |
setHeadComponents([ | |
<style | |
key="emotion-ssr" | |
data-emotion={`${docsCacheKey} ${ids.join(' ')}`} | |
dangerouslySetInnerHTML={{ | |
__html: patchedCss, | |
}} | |
/>, | |
]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment