Skip to content

Using module federation with emotion/context #370

@TheCodingGorilla

Description

@TheCodingGorilla

Setup

I've used the Next.js sidecar example and expanded to add a ThemeProvider from an internal component library that uses Emotion for styling.

Container Application

// _app.tsx
import Head from "next/head";
import { theme, Global, ThemeProvider } from '@internal/component-library';

export default function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider theme={theme}>
      <Head>
        <Global />
        <script src="http://localhost:8081/remoteEntry.js" />
      </Head>
      <Component {...pageProps} />
    </ThemeProvider>
  );
}
// index.tsx
import { lazy, Suspense } from "react";
import { dependencies } from "../../package.json";

const RemoteComponent = ({ scope, module, ...props }) => {
  if (!global[scope]) {
    return null;
  }

  global[scope].init({
    react: {
      [dependencies.react]: {
        get: () => Promise.resolve().then(() => () => require("react")),
      },
    },
  });

  const Component = lazy(() =>
    global[scope].get(module).then((factory) => factory())
  );

  return (
    <Suspense fallback={null}>
      <Component {...props} />
    </Suspense>
  );
};

export default function Home() {
  return (
    <div>
      <RemoteComponent scope="searchTeam" module="./ProductDetailsCard" propertyBedrooms="3" propertyId="12324" />
    </div>
  );
}

Remote module

// ProductDetailsCard.tsx

import React, { Component } from "react";
import { CardComponent } from '@internal/component-library';

const ProductDetailsCard = () => (
  <CardComponent
    isPremium={true}
  />
)

export default ProductDetailsCard;

Error

The above error occurred in the <Context.Consumer> component:
in Styled(div) (created by CardComponent)
in CardComponent (created by Context.Consumer)
in Styled(CardComponent) (created by ProductDetailsCard)
in ProductDetailsCard (at pages/index.tsx:23)
in Suspense (at pages/index.tsx:22)
in RemoteComponent (at pages/index.tsx:31)
in div (at pages/index.tsx:30)
in Home (at _app.tsx:12)
in ThemeProvider (at _app.tsx:6)
in MyApp
in ErrorBoundary (created by ReactDevOverlay)
in ReactDevOverlay (created by Container)
in Container (created by AppContainer)
in AppContainer
in Root
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.

Things tried

  • Setting remote @internal/component-library to eager and to singleton (it would be good to find documentation on what these are doing)
  • Removing remote dependencies (made no difference)

Any help would be very appreciated !

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions