forked from cometkim/gatsby-plugin-linaria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-ssr.js
54 lines (50 loc) · 1.41 KB
/
gatsby-ssr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import React from 'react'
import { renderToString } from 'react-dom/server'
import { collect } from 'linaria/server'
const LINARIA_STYLESHEET_RULE = /\/linaria\.[\w\d]+\.css$/
let bodyHTML
export const replaceRenderer = ({ bodyComponent }) => {
bodyHTML = renderToString(bodyComponent)
}
export const onPreRenderHTML = ({
pathname,
getHeadComponents,
replaceHeadComponents,
getPostBodyComponents,
replacePostBodyComponents,
}) => {
let styles = []
const headComponents = getHeadComponents().filter(({ type, props }) => {
if (type === 'style' && LINARIA_STYLESHEET_RULE.test(props['data-href'])) {
styles.push({
href: props['data-href'],
text: props.dangerouslySetInnerHTML.__html,
})
return false
}
return true
})
const { critical } = collect(
bodyHTML,
styles.map(style => style.text).join('')
)
// Attach critical CSS into top of head
replaceHeadComponents([
<style
key="linaria-critical-css"
data-linaria-critical={pathname}
dangerouslySetInnerHTML={{ __html: critical }}
/>,
...headComponents,
])
// Attach other and critical into bottom of body
// This also includes critical css because of cache hit
replacePostBodyComponents([
...getPostBodyComponents(),
styles
.map(style => style.href)
.map(href => (
<link key={href} rel="stylesheet" type="text/css" href={href} />
)),
])
}