This plugin adds support for server-side rendering, minification of styles, and a nicer debugging experience.
yarn add babel-plugin-styled-components --dev
Then add it to your babel configuration like so:
{
"plugins": ["babel-plugin-styled-components"]
}
That’s because styled-components needs an extra step to make sure the css class names are kept the same on the client side and server side.
babel plugin 讓 classs name 在 client 端和 server 端維持一致
styled-components SSR
The basic idea is that everytime you render your app on the server, you can create a ServerStyleSheet and add a provider to your React tree, that accepts styles via a context API.
每次在 server 端 render 時,產生 ServerStyleSheet 和增加一個 provider 在 React tree,這樣就可以透過 context API 接收 styles
Example
The basic API goes as follows:
import { renderToString } from 'react-dom/server'
import { ServerStyleSheet } from 'styled-components'
const sheet = new ServerStyleSheet()
try {
const html = renderToString(sheet.collectStyles(<YourApp />))
const styleTags = sheet.getStyleTags() // or sheet.getStyleElement();
} catch (error) {
// handle error
console.error(error)
} finally {
sheet.seal()
}
sheet.getStyleTags() : returns a string of multiple
styled-components SSR 設定
基礎概念範例
src/client/App.js
src/client/Html.js :
src/server.js
<App />
中的所有 styled 組件創建一個Style Sheet。這個樣式表等等會傳入 Html 模板。babel-plugin-styled-components
This plugin adds support for server-side rendering, minification of styles, and a nicer debugging experience.
Then add it to your babel configuration like so:
That’s because styled-components needs an extra step to make sure the css class names are kept the same on the client side and server side. babel plugin 讓 classs name 在 client 端和 server 端維持一致
styled-components SSR
The basic idea is that everytime you render your app on the server, you can create a ServerStyleSheet and add a provider to your React tree, that accepts styles via a context API. 每次在 server 端 render 時,產生 ServerStyleSheet 和增加一個 provider 在 React tree,這樣就可以透過 context API 接收 styles
Example The basic API goes as follows: