Extracting static HTML and CSS from Material-UI components in a TypeScript React app running in a browser environment

465 views Asked by At

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.

0

There are 0 answers