CSS-in-JS

一些 CSS-in-JS 工具允许我们在服务器端将页面渲染为 HTML 时收集页面的样式

这使我们能够将样式添加到 HTML,以便浏览器在加载 JavaScript 之前加载样式

// renderer/_default.page.server.jsx

import ReactDOMServer from "react-dom/server";
import React from "react";
import { escapeInject, dangerouslySkipEscape } from "vite-plugin-ssr";
import { CssCollector } from "some-css-in-js-tool";

export { render };

function render(pageContext) {
  const { Page } = pageContext;
  const page = <Page />;

  const collect = new CssCollector();

  const pageHtml = ReactDOMServer.renderToString(collect(page));

  // `vite-plugin-ssr` 在 HTML 末尾插入 `<script>` 标签
  // 浏览器将首先加载 `<style>` 标签
  return escapeInject`<!DOCTYPE html>
    <html>
      <head>
        <style>${dangerouslySkipEscape(collect.getCSS())}</style>
      </head>
      <body>
        <div id="page-view">${dangerouslySkipEscape(pageHtml)}</div>
      </body>
    </html>`;
}