You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生产环境下Gatsby+Mantine项目CSS加载缓慢问题求助

修复Mantine + Gatsby CSS加载延迟问题

方案1:正确配置gatsby-plugin-mantine(推荐)

如果已经安装了gatsby-plugin-mantine,先确保插件配置正确,避免手动SSR配置冲突:

  1. 在gatsby-config.js中完善插件配置:
    module.exports = {
      plugins: [
        {
          resolve: "gatsby-plugin-mantine",
          options: {
            ssr: true, // 强制开启SSR样式注入
            theme: {
              colorScheme: "light", // 匹配你的主题配置
              // 其他主题自定义项...
            },
          },
        },
        // 其他插件(如gatsby-plugin-mdx等)
      ],
    };
    
  2. 删除gatsby-ssr.js中的replaceRenderer函数(保留onRenderBody如果需要),因为插件会自动处理SSR样式注入,手动配置会覆盖插件逻辑导致样式丢失。
  3. 重新执行yarn build && yarn serve验证效果。

方案2:修正手动SSR配置(若不想用插件)

如果坚持手动配置SSR,需调整gatsby-ssr.js代码,确保使用Mantine的样式服务渲染:

/* eslint-disable react/jsx-filename-extension */
import React from "react";
import { createStylesServer, ServerStyles } from "@mantine/ssr";
import { MantineProvider } from "@mantine/core";

const stylesServer = createStylesServer();

// 包裹页面元素,确保MantineProvider生效
export const wrapPageElement = ({ element }) => {
  return <MantineProvider>{element}</MantineProvider>;
};

export const replaceRenderer = ({
  bodyComponent,
  replaceBodyHTMLString,
  setHeadComponents,
}) => {
  // 使用Mantine的stylesServer.renderToString收集样式
  const html = stylesServer.renderToString(bodyComponent);
  setHeadComponents([
    <ServerStyles server={stylesServer} key="mantine-styles" />,
  ]);
  replaceBodyHTMLString(html);
};

export const onRenderBody = ({ setHtmlAttributes }) => {
  setHtmlAttributes({ lang: "en" });
};

关键修改:用stylesServer.renderToString替代react-dom/server的renderToString,这样Mantine才能收集SSR期间生成的样式并注入到HTML头部。

方案3:提前加载全局样式

确保Mantine的全局样式被提取到Gatsby的主CSS bundle中,避免客户端动态加载:

  1. 创建src/styles/global.css文件,导入Mantine全局样式:
    @import "@mantine/core/styles.css";
    
  2. 在gatsby-browser.js和gatsby-ssr.js中导入该文件:
    import "./src/styles/global.css";
    
  3. 重新构建项目,全局样式会被Gatsby提前打包到首屏加载的CSS文件中。

额外检查点

  • 确认@mantine/ssr版本与@mantine/core一致(均为6.0.11),版本不匹配会导致SSR逻辑失效。
  • 执行yarn clean清除Gatsby缓存后重新构建,避免缓存旧配置或样式。

内容的提问来源于stack exchange,提问作者Ray Orole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 11:22:50