1

I have a TypeScript React application that uses Material-UI (MUI) for styling components. I need to extract the static HTML and CSS for a specific part of the component tree while running the application in a browser environment. I've tried using the @emotion/server package with the extractCritical function, but I'm encountering issues with missing polyfills for the Buffer and stream modules.

Here's a simplified version of my code:

import { renderToString } from 'react-dom/server';
import createEmotionServer from '@emotion/server/create-instance';
import createCache from '@emotion/cache';
import ExtractedComponent from './ExtractedComponent';

const cache = createCache({ key: 'mui' });
const { extractCritical } = createEmotionServer(cache);

const myComponent = (
  <CacheProvider value={cache}>
    <ExtractedComponent />
  </CacheProvider>
);

const { html, css } = extractCritical(renderToString(myComponent));

// Save the extracted HTML and CSS

I've tried configuring the necessary polyfills for the Buffer and stream modules, but I keep running into different issues. I also tried using the cheerio package to extract the styles, but it doesn't work with MUI's Theme approach.

Additionally, I have attempted to adapt the Server-Side Rendering (SSD) solution from MUI's documentation (https://mui.com/material-ui/guides/server-rendering/) for my use case, but I haven't been successful.

How can I properly extract the static HTML and CSS for MUI components while running the application in a browser environment? Any help or alternative solutions would be greatly appreciated.

Olivier Tassinari
  • 8,238
  • 4
  • 23
  • 23
supermodo
  • 675
  • 6
  • 15
  • First i think u need a `ref` for the React component that u want to "extract". then u can use `innerHtml` and `getComputedStyle` ... or u can try `XMLSerializer` – Tamás Katona Apr 06 '23 at 08:26

0 Answers0