vitejs / vite-plugin-react-swc

Speed up your Vite dev server with SWC
MIT License
831 stars 54 forks source link

Get "React refresh runtime was loaded twice." on the micro-frontend project #87

Closed dnshi closed 1 year ago

dnshi commented 1 year ago

Background

I am working on a micro-frontend project that a root container fetches and renders some applications' components, which are served on different vite dev servers (the applications are owned by different teams and have their own vite config).

To sync between the react refresh instance, I used RefreshRuntime.injectIntoGlobalHook(window); to share the state. But after I upgraded the version of vite-plugin-react-swc , with this change, https://github.com/vitejs/vite-plugin-react-swc/commit/e272817cf30418f62b06bc69e22371f2b9c0f6b1, I got the following message:

Error: React refresh runtime was loaded twice. Maybe you forgot the base path?
    at http://localhost:3001/@react-refresh:368:9

I understand the purpose of throwing the error, so want to ask if you have any suggestion to handle my use case? Maybe add a flag to detect whether injectIntoGlobalHook is used before throwing the error message? Thanks.

ArnaudBarre commented 1 year ago

To sync between the react refresh instance, I used RefreshRuntime.injectIntoGlobalHook(window); to share the state.

Not sure I get this, for me this "preamble code" should run also exactly once (per window).

Your setup is kind of particular. If code happens to run on the page at this end I think this should be served by the same dev server. You could still have something like /src/app1, src/app2 with specific app code and each once has its own React root container and lifecycle. How so you handle the fact that React is loaded only once?

Without more context, my advice would be to chose one dev server that owns the responsibility for injecting preamble and serving the runtime code and add a plugin in others vite dev server that rewrite the /@react-refresh import (after the plugin has transformed it) to be the one served by the main dev server

dnshi commented 1 year ago

Thanks for the advice! I am going to update my code and rewrite the /@react-refresh import.