Skip to content

Commit 39bb3dc

Browse files
authored
chore(website): fix ssr warning in dev (#99)
1 parent 1766620 commit 39bb3dc

File tree

3 files changed

+35
-3
lines changed

3 files changed

+35
-3
lines changed

website/next.config.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ module.exports = {
99
compiler: {
1010
styledComponents: true,
1111
},
12-
reactStrictMode: true,
12+
// ensure counter won't be incremented twice
13+
reactStrictMode: false,
1314
webpack: (config, options) => {
1415
config.resolve.alias = {
1516
...config.resolve.alias,

website/src/constants.ts

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,42 @@ import { codeBlock } from 'common-tags'
55
// @ts-ignore
66
import hn from '!!raw-loader!./pages/examples/hacker-news.tsx'
77

8+
// mimic babel plugin's behaviour to support SSR
9+
let counter = 0
10+
function hijackedStyled(...args: any[]) {
11+
// @ts-ignore
12+
return styled(...args)
13+
}
14+
const hash = 'runner'
15+
const ignoredProps = Object.getOwnPropertyNames(Function)
16+
Object.getOwnPropertyNames(styled).forEach((tag) => {
17+
if (ignoredProps.includes(tag)) return
18+
Object.defineProperty(hijackedStyled, tag, {
19+
get() {
20+
return styled[tag].withConfig({
21+
componentId: `sc-${hash}-${counter++}`,
22+
})
23+
},
24+
})
25+
})
26+
27+
export const resetCounter = () => {
28+
counter = 0
29+
}
30+
831
export const scope = {
932
...React,
10-
styled,
33+
styled: hijackedStyled,
1134
css,
1235
keyframes,
1336
createGlobalStyle,
1437
import: {
1538
react: React,
16-
'styled-components': Styled,
39+
'styled-components': {
40+
...Styled,
41+
default: hijackedStyled,
42+
__esModule: true,
43+
},
1744
},
1845
}
1946

website/src/pages/_document.tsx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import Document, {
77
} from 'next/document'
88
import { ServerStyleSheet } from 'styled-components'
99

10+
import { resetCounter } from '../constants'
11+
1012
export default class MyDocument extends Document {
1113
static async getInitialProps(ctx: DocumentContext) {
1214
const sheet = new ServerStyleSheet()
@@ -35,6 +37,8 @@ export default class MyDocument extends Document {
3537
}
3638

3739
render() {
40+
// reset counter for SSR
41+
resetCounter()
3842
return (
3943
<Html lang="en" data-theme="system">
4044
<Head />

0 commit comments

Comments
 (0)