vite-plugin-federation
vite-plugin-federation copied to clipboard
Zustand in remote app causes issues
Versions
- vite-plugin-federation: ^1.2.3
- vite: ^4.4.9
Reproduction
There is an issue if you install zustand as a state manager in a remote app.
I did some research and noticed that zustand has use-sync-external-store as a dependency (here), which is bundled in cjs and in its turn imports react as a commonjs module: require("react").
It causes two issues:
- remote app adds an additional import in the build output:
import { r as reactExports, g as getDefaultExportFromCjs } from './__federation_shared_react.js'; - host app loads "__federation_shared_react.js" twice in the Chrome Network tab.
However, this reactExports is undefined which results in an error: Error: Cannot read properties of undefined (useRef).
Here is a github repo that you can clone and reproduce the issue there.
Extra import in the remote app output:
Commonjs import of "react" in "use-sync-external-store" package:
Steps to reproduce
- clone the repo;
- install modules using
pnpm installin the root of the project; - run
pnpm build && pnpm serve; - open host app and observe an error in the console.
What is Expected?
- Shared react is loaded only once;
- There is no additional import in the remote app build output;
- There is no errors in the console.
I have cloned your repo to check it out, and I will give the following workaround:
- In host , please install more zustand
- In both the host and remote vite.config.ts directories, add the configuration:
federation({
...
shared:{
zustand:{}
}
})
- In Remote, at the counter.jsx directory change the import of zustand:
change: import {create} from "zustand";
to: import create from "zustand";
- build & start
If you want a reference on how to share state between host and remote using zustand, you can refer to my repo Checkout
@nguyenbatranvan thanks for the response! Eventually, I've come to this workaround as well, that said if we I add a few more libraries that use commonjs imports I'll have to add them to the host app too (even if host app doesn't need them at all).
have you tried downgrade vite-plugin-federation to v1.1.14?
Same issue happens with swr. Downgrading to 1.1.14 seems to have solved the problem.
@AsuraKev, @tpreusse Thanks guys, downgrading the version did help me.
Hey all, is there a recent solution or a plan for resolving this? The version 1.1.14 is now already rather old
The workaround of adding the package also to the host works, but is still just a workaround imho
I still got error even downgrading to 1.1.14 (for host and remote)