Sharing code at runtime

Module Federation

14 Jul 2021

Adrian Fâciu

Module Federation

The problem

Some existing solutions

NPM

Micro frontend frameworks

Single build

All have (some) problems that we want to avoid

Enter

module federation

Allow us to share code from one build to another

but

Webpack (5)

Webpack (5)

Webpack (5)

esbuild

and

Webpack/esbuild

Module federation is core webpack

General overview

Terminology

Live demo

with React

React Suspense

“wait” for some code to load and specify a loading state

// Lazy-loaded
const ProfilePage =
      React.lazy(() => import('./ProfilePage')); 


// Show a spinner while the profile is loading
<Suspense fallback={<Spinner />}>
  <ProfilePage />
</Suspense>

Demo time

Other features

Omnidirectional host

Dependency management

new ModuleFederationPlugin({
      name: "appb",
      filename: "remoteb.js",
      exposes: {
        "./HelloFromB": "./src/HelloFromB",
      },
      shared: ["react", "react-dom"],
    }),
new ModuleFederationPlugin({
      name: "appb",
      filename: "remoteb.js",
      exposes: {
        "./HelloFromB": "./src/HelloFromB",
      },
       shared: {
         "react": { singleton: true },
         "react-dom": { singleton: true }
       },
    }),
const deps = require("./package.json").dependencies;
...
new ModuleFederationPlugin({
      name: "appb",
      filename: "remoteb.js",
      exposes: {
        "./HelloFromB": "./src/HelloFromB",
      },
      shared: {
         ...deps,
         "react": { singleton: true, 
                   requiredVersion: deps["react"] },
         "react-dom": { singleton: true,
                       requiredVersion: deps["react-dom"] }
       },
    }),

Demo again

We also get

- circular imports

- nested remotes

- webpack 4 support (sort of)

Error handling

- need ErrorBoundary

- bootstrapping applications

- fallback to existing functionality

Benefits

- expose and use any module type that webpack/esbuild supports

-  environment-independent

-  dependency management

Suport status from major players

React

Out of the box if no CRA

- eject

Angular

Out of the box if no Angular CLI

- @angular-architects/module-federation-plugin

- eject

Vue

Out of the box if no Vue CLI

- Vue CLI 5 will support Webpack 5

- eject

Others

- svelte

- typescript

- web components

- next.js

- rollup plugin (to consume)

Module federation

&

Micro frontend frameworks

Module federation

&

NPM

Alternate deployment methods

Module federation

Drawbacks

- webpack/esbuild

- not fully adopted (yet)

- runtime loading

Resources

Questions?