module-federation / core

Module Federation is a concept that allows developers to share code and resources across multiple JavaScript applications
https://module-federation.io/
MIT License
1.26k stars 180 forks source link

Next SSR with two react remotes #2521

Open ulrichgreen opened 1 month ago

ulrichgreen commented 1 month ago

Describe the bug

I previously found out via this issue that React needs to be marked as external when using it in a common-js remote on the server.

Now I face an issue where I have two remotes and using those in the Next.js host. In my reproduction below I have "remote" exposing two components, which both "remote2" and "host" is using. And when I import components from remote2 and rendering those in the host, I get the same error as in the original issue: `Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."

Both remotes have marked react/react-dom as external.

If I only use the first remote, it works fine: https://github.com/ulrichgreen/nextjs-mf/blob/main/host/src/pages/index.tsx#L7

I have a feeling that I need a runtime plugin of sorts to to tell remote2 that it should use the react in host for the remote it has defined? But I cant find any examples on anything related that can point me in any direction :)

Using latest mf related packages

Reproduction

https://github.com/ulrichgreen/nextjs-mf

Used Package Manager

npm

System Info

System:
    OS: macOS 14.5
    CPU: (10) arm64 Apple M2 Pro
    Memory: 1009.11 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.11.0 - ~/Library/Caches/fnm_multishells/55507_1715949432950/bin/node
    npm: 10.2.4 - ~/Library/Caches/fnm_multishells/55507_1715949432950/bin/npm
    pnpm: 8.9.0 - ~/Library/pnpm/pnpm
  Browsers:
    Chrome: 124.0.6367.209
    Safari: 17.5

Validations

ScriptedAlchemy commented 1 month ago

If react is external then don't share it in that build. Will take a look at repo tomorrow or day after

ulrichgreen commented 1 month ago

Hmm in what build, remote or remote2? And only the server build? In any case... I tried all combinations of sharing/ not sharing react between remote, remote2 and host in the repro. I either get the above error or "Cannot access "ButtonFederated" before its initialized"

ulrichgreen commented 1 week ago

@2heal1 I saw your PR on hostShareScopeMap - I have a feeling that it could help here. I could not find any info on it, other than the plugin example in the PR. But apparently Im too thick headed to undstand exactly what it is :) Can you explain the use case for hostShareScopeMap?