Skip to content

Instantly share code, notes, and snippets.

@emmenko
Last active January 7, 2021 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emmenko/b9debcf4be523d00ee1eee314896aa5f to your computer and use it in GitHub Desktop.
Save emmenko/b9debcf4be523d00ee1eee314896aa5f to your computer and use it in GitHub Desktop.
Patch Emotion SSR for Lobotomized Owl selectors
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