Skip to content

Importing react-dom/server in client bundle for renderToStaticMarkup #544

@bensaufley

Description

@bensaufley

I was wondering why my bundle size added 200kb when I added @highcharts/react even though I've got highcharts as an external dependency in my Vite config and this package seems pretty small. After some digging I discovered react-dom was being bundled with a lot of server stuff – unexpected, since the code is not being used in an SSR environment and is client-only. Looking through the code, I found:

import { renderToStaticMarkup } from "react-dom/server";

I'm pretty sure I have some options to shim around this, and I'll continue to work down that road, but in the meantime I thought I'd mention this here.

According to the React docs:

renderToStaticMarkup works in the browser, but using it in the client code is not recommended. If you need to render a component to HTML in the browser, get the HTML by rendering it into a DOM node.

The suggestion at the link there is pretty simple:

import { createRoot } from 'react-dom/client';
import { flushSync } from 'react-dom';

const div = document.createElement('div');
const root = createRoot(div);
flushSync(() => {
  root.render(<MyIcon />);
});
console.log(div.innerHTML); // For example, "<svg>...</svg>"

Would that, or something like it, work for the @highcharts/react use case? If so, I'm happy to create a PR.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions