originjs / vite-plugin-federation

Module Federation for vite & rollup
Other
2.4k stars 242 forks source link

Dynamic Remotes with React #526

Closed dk-v closed 1 year ago

dk-v commented 1 year ago

Versions

Reproduction

I am trying to get the dynamic remotes feature to work with React but so far I've been unsuccessful. It appears like the remote module is fetched successfully but when I try to render the remote an error occurs. I would appreciate if someone could point out if I am doing something wrong.

Additional Details
Host `App.tsx` ```Javascript function App() { const [count, setCount] = useState(0); const [DynamicRemote, setDynamicRemote] = useState(); useEffect(() => { __federation_method_setRemote("dyn", { url: () => Promise.resolve("http://localhost:4201/assets/remoteEntry.js"), format: "esm", from: "vite", }); __federation_method_getRemote("dyn", "./DynamicApp") .then((moduleWrapped) => __federation_method_unwrapDefault(moduleWrapped)) .then((module) => { setDynamicRemote(module); }); }, []); if (DynamicRemote) { return ( <>

Test dynamic remotes

); } else { return

Loading...

; } export default App; ``` Host `vite.config` ``` Javascript export default defineConfig({ plugins: [ react(), federation({ name: "shell", remotes: { dyn: "", }, shared: ["react", "react-dom"], }), ], server: { port: 4200, }, build: { target: "esnext", cssCodeSplit: false, minify: false, modulePreload: false, }, }); ``` Remote `App.tsx` ```Javascript function App() { return ; } export default App; ``` Remote `vite.config` ```Javascript export default defineConfig({ plugins: [ react(), federation({ name: "dyn", filename: "remoteEntry.js", exposes: { "./DynamicApp": "./src/App", }, shared: ["react", "react-dom"], }), ], server: { port: 4201, }, build: { target: "esnext", cssCodeSplit: false, minify: false, modulePreload: false, }, }); ```

Steps to reproduce

  1. Build the remote and start the remote.
  2. Start the Host and open Dev Tools.

What is Expected?

The remote loads dynamically and can be rendered like normal.

What is actually happening?

I am getting the following errors when trying to render the remote: image

eduardklinger commented 1 year ago

It's working for me.

Just set your state variable like this:

setDynamicRemote(() => module);

dk-v commented 1 year ago

Thanks, that worked for me when I run the host with pnpm dev. However, when I try to build the host and run it via pnpm preview I get an error that the shareScope is not defined. grafik

Do you have any suggestions how I could fix this error?

dk-v commented 1 year ago

Ok, I figured it out. My problem was that I left the remotes property completely empty. You have to at least put some sort of placeholder there.

remotes: {
    placeholder: "",
}