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.51k stars 231 forks source link

Error: Shared module react doesn't exist in shared scope default #1104

Closed gdunix closed 1 year ago

gdunix commented 1 year ago

Getting this error when trying to use the new app router with @module-federation/nextjs-mf

Server Error
Error: Shared module react doesn't exist in shared scope default

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
ensureExistence
file:///Users/georgiosntounis/Documents/test-projects/next-mfe/.next/server/webpack-runtime.js (881:68)

Here is what I have in my next.config.js file

const NextFederationPlugin = require("@module-federation/nextjs-mf");

const remotes = () => {
  return {
    "my_components": `my_components@http://localhost:8082/remoteEntry.1.0.0.js`,
  };
};

const nextConfig = {
  webpack(config, { isServer }) {
      config.plugins.push(
        new NextFederationPlugin({
          name: "host",
          filename: "static/chunks/remoteEntry.js",
          remotes: remotes(),
          shared: {},
        })
      );
    return config;
  },
};

module.exports = nextConfig;
yspychala commented 1 year ago

AFAIK, App dir isn’t supported yet. But I read it was planed after the release of v7.

gpatatoukas commented 1 year ago

Great to hear there's a plan in place! Any chance you could ballpark when we might see a solution? Also, is there a quick fix we can use in the meantime?

yspychala commented 1 year ago

I’m not a maintainer so I cannot speak in their names. You may follow some issues that are already talking about this: https://github.com/module-federation/universe/issues/619 and https://github.com/module-federation/universe/issues/799#issuecomment-1521057214

ScriptedAlchemy commented 1 year ago

yes RSC will get support eventually. With v7 now done, if the community wants to help (i know a few were interested in trying a few things) - im happy for extra hands.

First step i need is a PR of my repo using and breaking with app dir, then ill see what needs to be done to make it not error haha.

ll-shiyi commented 1 year ago

Same issue, any solution here?

jmilind1234 commented 1 year ago

I'm also getting same error as that @gdunix is facing. Did anyone found solution? @ScriptedAlchemy @yspychala @gpatatoukas

giovanniantonaccio commented 1 year ago

@ScriptedAlchemy do you mean a PR creating a new example in this repo?

nameofname commented 1 year ago

@ScriptedAlchemy I was just working on this... you can use my repo, created a branch which shows the issue clearly : https://github.com/nameofname/next-module-federation/tree/nameofname/app-router-error/mfe2

Inside the dir mfe2/src there are 2 directories, app and pages-bak ... both are bare bones examples of app router and pages router. I tested locally and if I run npm run dev from within mfe2 then I will encounter the error.

If I mv app app-bak && mv pages-bak pages then cd.. && npm run dev then the error will go away.

nameof ~/github/next-module-federation/mfe2 (nameofname/app-router-error) # npm run dev

> mfe2@1.0.0 dev
> rm -rf .next; next dev -p 3002

- ready started server on 0.0.0.0:3002, url: http://localhost:3002
[nextjs-mf]: automaticAsyncBoundary is deprecated
[nextjs-mf]: automaticAsyncBoundary is deprecated
(node:18010) [DEP_WEBPACK_MODULE_ID] DeprecationWarning: Module.id: Use new ChunkGraph API
(Use `node --trace-deprecation ...` to show where the warning was created)
- event compiled client and server successfully in 240 ms (107 modules)
- wait compiling...
- event compiled client and server successfully in 112 ms (107 modules)
- wait compiling /page (client and server)...
- event compiled client and server successfully in 1677 ms (478 modules)
- error Error: Shared module react doesn't exist in shared scope default
    at ensureExistence (/Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:800:68)
    at /Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:878:13
    at /Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:863:20
    at webpack/sharing/consume/default/react (/Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:915:74)
    at /Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:959:56
    at Array.forEach (<anonymous>)
    at __webpack_require__.getEagerSharedForChunkId (/Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:928:36)
    at /Users/nameof/github/next-module-federation/mfe2/.next/server/app/page.js:1869:72
    at Object.<anonymous> (/Users/nameof/github/next-module-federation/mfe2/.next/server/app/page.js:1882:3)
    at Module._compile (node:internal/modules/cjs/loader:1149:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1203:10)
    at Module.load (node:internal/modules/cjs/loader:1027:32)
    at Module._load (node:internal/modules/cjs/loader:868:12)
    at Module.require (node:internal/modules/cjs/loader:1051:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at requirePage (/Users/nameof/github/next-module-federation/mfe2/node_modules/next/dist/server/require.js:156:12)
    at /Users/nameof/github/next-module-federation/mfe2/node_modules/next/dist/server/load-components.js:71:84
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async loadComponentsImpl (/Users/nameof/github/next-module-federation/mfe2/node_modules/next/dist/server/load-components.js:71:26)
    at async DevServer.findPageComponentsImpl (/Users/nameof/github/next-module-federation/mfe2/node_modules/next/dist/server/next-server.js:772:36) {
  digest: undefined
}
- wait compiling /_error (client and server)...
- event compiled client and server successfully in 478 ms (573 modules)
marcelongf commented 1 year ago

@ScriptedAlchemy You still want some error examples related to app dir? I've been trying to import remotes within the app dir for a while now but without any success... I can hand you some examples

ScriptedAlchemy commented 1 year ago

Yes please, really the main blocker beyond getting v7 done and starting a new job, historically it was i didnt have the time to reproduce some cases to work against, so instead of diverting time from v7 to see what needed to be done, i delayed the efffort till later. If you have a repo thats nice and broken, thats about 50% of the effort :)

nameofname commented 1 year ago

@ScriptedAlchemy I created an example of this error happening in a fork of module-federation-examples. In this commit I tried to take the page layout files you had and re-work them into an app dir.

Steps :

... the same error occurs :

[nextjs-mf]: automaticAsyncBoundary is deprecated
(node:34832) [DEP_WEBPACK_MODULE_ID] DeprecationWarning: Module.id: Use new ChunkGraph API
(Use `node --trace-deprecation ...` to show where the warning was created)
[nextjs-mf]: automaticAsyncBoundary is deprecated
- info Creating an optimized production build  
- info Compiled successfully
- info Linting and checking validity of types  
- info Collecting page data ..Error: Shared module react doesn't exist in shared scope default
    at ensureExistence (/Users/nameof/projects/module-federation-examples/nextjs-ssr/home/.next/server/webpack-runtime.js:1263:68)
    at Function.<anonymous> (/Users/nameof/projects/module-federation-examples/nextjs-ssr/home/.next/server/webpack-runtime.js:1341:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Promise.all (index 0)
    at async Promise.all (index 1)
    at async loadComponentsImpl (/Users/nameof/projects/module-federation-examples/nextjs-ssr/home/node_modules/next/dist/server/load-components.js:80:26)
    at async /Users/nameof/projects/module-federation-examples/nextjs-ssr/home/node_modules/next/dist/build/utils.js:1006:32
    at async Span.traceAsyncFn (/Users/nameof/projects/module-federation-examples/nextjs-ssr/home/node_modules/next/dist/trace/trace.js:103:20)

> Build error occurred
Error: Failed to collect page data for /
    at /Users/nameof/projects/module-federation-examples/nextjs-ssr/home/node_modules/next/dist/build/utils.js:1156:15
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  type: 'Error'
}
- info Collecting page data .npm ERR! Lifecycle script `build` failed with error: 
npm ERR! Error: command failed 
npm ERR!   in workspace: nextjs-ssr_home@0.1.0 
npm ERR!   at location: /Users/nameof/projects/module-federation-examples/nextjs-ssr/home 
Muskos commented 1 year ago

Hi @ScriptedAlchemy You don't need any complex examples. https://github.com/Muskos/nextjs-mf-app-folder Here is just the Nextjs app with @module-federation/nextjs-mf plugin and one page in the app folder. You can reproduce it here.

ll-shiyi commented 1 year ago

I try to run this project: https://github.com/Muskos/nextjs-mf-app-folder same error shows: Error: Shared module react doesn't exist in shared scope default

Have you tested it yourself?

Hi @ScriptedAlchemy You don't need any complex examples. https://github.com/Muskos/nextjs-mf-app-folder Here is just the Nextjs app with @module-federation/nextjs-mf plugin and one page in the app folder. You can reproduce it here.

arnoBruynseels commented 1 year ago

Same issue here.

As mentioned in this comment it will hopefully be fixed in v7.1.

Here is the changelog.

dylan-reniers-digitalum commented 1 year ago

@arnoBruynseels @ScriptedAlchemy is there a beta version we could use for testing?

hemanthkatam commented 1 year ago

facing same issue here

marcelino-borges commented 1 year ago

Same here

Is there any update on this?

I was migrating a whole project to the new "app" routing, but then started to face this error ='(

ttdat2510 commented 1 year ago

+1 same here...

dvynograd commented 1 year ago

+1 here.

Has anybody found a workaround for the app router with nextjs 13.4 with module-federation

sscotth commented 1 year ago

we will likely implement it first in modernjs.dev, then see how to backport it to next. If it can be

https://github.com/module-federation/universe/issues/1183#issuecomment-1692590649

vincentarck commented 1 year ago

any update friend ? please let me know, currently having same trouble. and i found this thread, about paid one nextjs-mf, whats the diffrence from free one ? https://www.privjs.com/packages/%40module-federation%2Fnextjs-mf?pkg=@module-federation/nextjs-mf

bernardonascimento commented 1 year ago

+1

sscotth commented 1 year ago

any update friend ? please let me know, currently having same trouble. and i found this thread, about paid one nextjs-mf, whats the diffrence from free one ? https://www.privjs.com/packages/%40module-federation%2Fnextjs-mf?pkg=@module-federation/nextjs-mf

https://github.com/module-federation/module-federation-examples/discussions/978

ScriptedAlchemy commented 1 year ago

Open to PRs for this longstanding issue. Modern.js will support RSC before Next.js due to its open-source priority. It's easier to implement in Modern.js, which has an unparalleled Developer Experience (DX) for Micro Frontends (MFE). The focus is on releasing the internal version to the open-source community, offering a meta-framework for microfrontends and horizontal scaling—something unmatched in my consulting experience with other companies' in-house MFE or MFP efforts.

Planning a fork of Module Federation to release an enhanced version with broad support for TypeScript (TS), Hot Module Replacement (HMR), Server-Side Rendering (SSR), dynamic loading, automatic route stitching, middleware, and more. For details, see issue #1170.

Challenges with Next.js are significant; it's not designed for module federation. Enhancements are often complex or nearly impossible. For an in-depth understanding, refer to the InvertedContainerRuntimeModule on GitHub.

"Container Inversion" involves a complete overhaul of webpack's JSONP and dependency management systems. Despite its complexity, it has solved other architectural issues, especially with circular or nested remotes. This will be integrated into V1.5 of the forked federation. RSPack.dev plans to implement V1.5 in Rust by Q1, offering native support for Module Federation. Concurrently, I'll work with the Modern.js team to reorganize their internal fork and decouple it from our internal deployment infrastructure.

There's overlap between the needs of Modern.js and Next.js. Bytedance has solved many issues at scale, and my recent Next.js workarounds have led to beneficial patterns. These will be integrated into my module-federation ecosystem with web-infra-dev.

I'm currently integrating the node federation specification for Modern.js as we perfect SSR and backend integrations. Plans are underway to use federation in CI, build management, and Infrastructure as Code, necessitating a memory-efficient server solution.

Timeline predictions: RSC support in Next.js is at least 6 months away. If urgently needed, our consulting/pro services branch can fund it. Modern.js will likely have RSC Federation support 2-3 weeks after RSC itself is supported. Unless a breakthrough or business case allows for resource reallocation, the timeline remains uncertain. Expect more insights in 1-2 months.

URLs:

dhalbrook commented 1 year ago

I'm seeing this error and we're not using the app directory and are still on Next 12.

It will take a bit of time to get a sample repo together, but I'll work on it shortly. In the meantime, We're using the following:

"@module-federation/nextjs-mf": "6.7.1",
"@module-federation/typescript": "2.4.2",
"@module-federation/utilities": "^3.0.0"

and loading the remote via "importRemote".

What is super odd is that the S3-hosted remote works against my local Next instance in production mode, but when I run it on one our QA instances it throws this exception when attempting to load the remote (the remote returns 200 in both cases). We're only using client side rendering FWIW. My local box is compiling using OSX whereas our CI is Linux. The remote was compiled on my local instance before being uploaded to the S3 bucket. Does the OS have any effect on the webpack artifacts produced? I can't imagine it does, but I can't account for any other differences (other than my local running on http and the qa server running https).

I'm not sure it's helpful, but when I was using next/dynamic in the remote, the error message referenced not being able to load that module, until I changed it to use React.lazy.

ScriptedAlchemy commented 1 year ago

Suspense swallows the error. You should try v7 or 8 and see how that works. 6 is old and quite

dhalbrook commented 1 year ago

We are still on React 17 and Next 12. Switching to nextjs-mf 7.x causes new and different issues, one being webpack trying to dynamically load a bunch of node modules (Critical dependency: the request of a dependency is an expression) and then ultimately blowing up during SSR (RangeError: Maximum call stack size exceeded at RegExp.exec () at retrieveSourceMapURL).

EliakimGama commented 1 year ago

Hello, I'm facing the same issue

Server Error Error: Shared module react-dom doesn't exist in shared scope default This error occurred while generating the page. Any console logs will be displayed in the terminal window.

I'm using Next.js 13, is there any solution available?

ScriptedAlchemy commented 1 year ago

use v8 prerelease. https://github.com/module-federation/universe/issues/1530 next tag on npm. no RSC progress but less bugs

wanbinkimoon commented 12 months ago

I'm using v "@module-federation/nextjs-mf": "next", which translate into 8.0.1-4 and still experiencing the same error

Screenshot 2023-11-07 at 21 17 36
ScriptedAlchemy commented 11 months ago

use "canary" tags

bkirova commented 10 months ago

For me the solution was to wrap the NextFederationPlugin plugin in `if (!options.isServer) like in this example:

https://github.com/module-federation/module-federation-examples/blob/77715463a47233b8db7f1403e3865aa1de5acf52/nextjs-v13/home/next.config.js#L5

and add the following aliases in the same if condition:

  config.resolve.alias["react/jsx-runtime"] = path.join(
    __dirname,
    "/node_modules/react/jsx-runtime.js"
  );
  config.resolve.alias["react/jsx-dev-runtime"] = path.join(
    __dirname,
    "/node_modules/react/jsx-dev-runtime.js"
  );
  config.resolve.alias["react"] = path.join(
    __dirname,
    "/node_modules/react/index.js"
  );
rahimimo commented 10 months ago

Which version did you use? @bkirova For my case the page blinks and it is empty even if with your solution.

bkirova commented 10 months ago
"next": "13.5.6"
"react": "^18.2.0"
"react-dom": "^18.2.0"

Something very important is that i am using the "pages" directory instead of the new "app" directory! This might be also part of why this setup is working.

This is my entire next.config.js (I am also using experimental imports from Framer)

/** @type {import('next').NextConfig} */
const { NextFederationPlugin } = require("@module-federation/nextjs-mf");
const path = require("path");
const nextConfig = {
  reactStrictMode: true,
  distDir: "build",
  webpack(config, options) {
    if (!options.isServer) {
      config.resolve.alias["react/jsx-runtime"] = path.join(
        __dirname,
        "/node_modules/react/jsx-runtime.js"
      );
      config.resolve.alias["react/jsx-dev-runtime"] = path.join(
        __dirname,
        "/node_modules/react/jsx-dev-runtime.js"
      );
      config.resolve.alias["react"] = path.join(
        __dirname,
        "/node_modules/react/index.js"
      );

      config.plugins.push(
        new NextFederationPlugin({
          name: "DreamComponents",
          filename: "static/chunks/remoteEntry.js",
          exposes: {
            "./components": "./src/components/index.ts",
          },
          shared: {},
        })
      );
    }

    return config;
  },
  experimental: {
    urlImports: [
      "https://framer.com/m/",
      "https://framerusercontent.com/",
      "https://ga.jspm.io/",
      "https://jspm.dev/",
      "https://rive.app/",
      "https://boosters.flowbase.co/",
    ],
  },
};

module.exports = nextConfig;

I hope this helps. @rahimimo

rahimimo commented 10 months ago

Thanks a lot! @bkirova . I have already got it working with pages directory my issue was getting it to working with the AppRouter. @ScriptedAlchemy I have tried the latest canary but still it did not work. Is it supposed to work now with the app router and there is something wrong with my code or it is still not supposed to work? I am getting errors like app-index.js:128 Uncaught TypeError: (0 , _react.use) is not a function

ScriptedAlchemy commented 9 months ago

https://github.com/module-federation/universe/pull/2002

Ashin2052 commented 8 months ago
"next": "13.5.6"
"react": "^18.2.0"
"react-dom": "^18.2.0"

Something very important is that i am using the "pages" directory instead of the new "app" directory! This might be also part of why this setup is working.

This is my entire next.config.js (I am also using experimental imports from Framer)

/** @type {import('next').NextConfig} */
const { NextFederationPlugin } = require("@module-federation/nextjs-mf");
const path = require("path");
const nextConfig = {
  reactStrictMode: true,
  distDir: "build",
  webpack(config, options) {
    if (!options.isServer) {
      config.resolve.alias["react/jsx-runtime"] = path.join(
        __dirname,
        "/node_modules/react/jsx-runtime.js"
      );
      config.resolve.alias["react/jsx-dev-runtime"] = path.join(
        __dirname,
        "/node_modules/react/jsx-dev-runtime.js"
      );
      config.resolve.alias["react"] = path.join(
        __dirname,
        "/node_modules/react/index.js"
      );

      config.plugins.push(
        new NextFederationPlugin({
          name: "DreamComponents",
          filename: "static/chunks/remoteEntry.js",
          exposes: {
            "./components": "./src/components/index.ts",
          },
          shared: {},
        })
      );
    }

    return config;
  },
  experimental: {
    urlImports: [
      "https://framer.com/m/",
      "https://framerusercontent.com/",
      "https://ga.jspm.io/",
      "https://jspm.dev/",
      "https://rive.app/",
      "https://boosters.flowbase.co/",
    ],
  },
};

module.exports = nextConfig;

I hope this helps. @rahimimo

Does this configuration works with ssr? I mean when option.isServer true or when we need module federation with ssr?