ant-design / antd-style

css-in-js library with antd v5 token system
https://ant-design.github.io/antd-style/
MIT License
219 stars 35 forks source link

🧐[问题] 如何在Gatsby内使用ssr #49

Closed Jiohon closed 1 year ago

Jiohon commented 1 year ago

🧐 问题描述

请问在Gatsby内如何使用ssr, 是否有类似emotion/ssr的api

💻 示例代码

gatsby-ssr.jsx

import * as React from "react";
import { renderToString } from "react-dom/server";
import { extractCritical } from "@emotion/server";
import { cache } from "@emotion/css";
import { CacheProvider } from "@emotion/react";

export const replaceRenderer = ({
  replaceBodyHTMLString,
  bodyComponent,
  setHeadComponents,
}) => {
  const { html, ids, css } = extractCritical(
    renderToString(<CacheProvider value={cache}>{bodyComponent}</CacheProvider>)
  );
  setHeadComponents([
    <style
      key="emotion"
      data-emotion={`css ${ids.join(" ")}`}
      dangerouslySetInnerHTML={{
        __html: css,
      }}
    />,
  ]);
  replaceBodyHTMLString(html);
};

🚑 其他信息

Jiohon commented 1 year ago

目前使用的是这种方式,不知道有更好的方式没有?

export const replaceRenderer = ({ replaceBodyHTMLString, bodyComponent, setHeadComponents }) => {
  const html = renderToString(<>{bodyComponent}</>)

  const antdCache = (global as any).__ANTD_CACHE__
  const styles = extractStaticStyle(html, { antdCache }).map((item) => item.style)

  styles.forEach((item) => {
    setHeadComponents([
      <style
        key="emotion"
        data-emotion={`acss---`}
        dangerouslySetInnerHTML={{
          __html: item.props.dangerouslySetInnerHTML.__html,
        }}
      />,
    ])
  })
  replaceBodyHTMLString(html)
}