All writing

Sharing a design system with Module Federation

At work we have a couple dozen internal React apps, most of them webpack 5 builds, and they all share one design system, which is really two projects. A themes package holds the design itself (colors, typography, and how every MUI component should look for each of our brands), and a components project builds our own components on top of it and is deployed as a Module Federation remote that the apps load at runtime. This covers how both are set up, starting with the theme, since that’s the part designers work in too, and then the parts of the remote’s config I end up explaining most often to people joining the team.

The design lives in the theme

We use MUI, and early on we decided not to wrap its components in our own Button, Chip and so on just to restyle them. Instead the design goes into the theme, through MUI’s palette and typography, styleOverrides and defaultProps, and custom variants, so apps keep using the plain MUI components and get our look from the ThemeProvider above them. A button style from the design looks like this in the theme:

export const primaryButtons = [
  {
    props: { variant: 'primaryDefault' },
    style: ({ theme }) => ({
      ...buttonsCommon,
      color: `var(--text-light, ${theme.palette.text.light})`,
      backgroundColor: theme.palette.secondary.main,
      '&:hover': { backgroundColor: theme.palette.secondary.dark },
      '&:disabled': {
        backgroundColor: alpha(theme.palette.neutrals.primary, 0.3),
        color: `var(--text-disabled, ${theme.palette.text.disabled})`,
      },
    }),
  },
  // primaryHC, primaryAccent1, ...
];

In an app that’s just <Button variant="primaryDefault">, but MUI doesn’t know about our variants or the extra palette colors (neutrals, text.interactive and so on), so the package also ships a theme-config.d.ts that adds them to MUI’s types with module augmentation, which is what makes that variant type-check:

declare module '@mui/material/Button' {
  interface ButtonPropsVariantOverrides {
    primaryDefault: true;
    primaryHC: true;
    // ...
  }
}

Some colors are written as a CSS variable with the theme value as the fallback, like the var(--text-light, …) above, which lets a page that embeds one of our apps change a color with a CSS variable without waiting for a new theme release.

The package has one folder per brand (we have a handful of them, with the enterprise apps being one), each with its own palette, typography, buttons, chips and alerts, plus a shared folder that every brand builds on. The top of the shared provider starts with a big “DANGER ZONE” comment, because a change there reaches every brand at once, and brand-specific changes are supposed to go into the brand’s own files. That provider also uses MUI’s ScopedCssBaseline instead of CssBaseline, so MUI’s style reset only applies inside our app’s root and not to the whole page, which matters once an app is loaded inside another one.

Since a change to the design is mostly a change to a palette value or a variant’s style object, in a file named after the component, the theme is something designers can work in as well, and both designers and developers keep it up to date with the design. Commits follow conventional commits and semantic-release publishes a new version on every merge to main, so a feat: from a designer becomes a new minor version the same way a developer’s does.

The components remote

The components project is one webpack build with a ModuleFederationPlugin that exposes every component, hook and theme file as its own entry (trimmed here, the real list is a lot longer):

const { ModuleFederationPlugin } = require('webpack').container;

new ModuleFederationPlugin({
  name: 'shared_components',
  filename: 'remoteEntry.js',
  exposes: {
    './NavBar': './src/components/NavBar',
    './Table': './src/components/Table',
    './Form': './src/components/Form',
    './SimpleDialog': './src/components/SimpleDialog',
    './hooks': './src/hooks',
    './theme': './src/theme',
    './palette': './src/theme/palette',
    './utils': './src/utils',
  },
  shared: { /* more on this below */ },
});

With output.publicPath set to 'auto', so the chunks load from wherever remoteEntry.js is served and not from the host’s origin, a host can then do import('shared_components/NavBar') and get whatever is deployed at that moment, as long as remoteEntry.js itself isn’t cached (ours is served with must-revalidate, while the content-hashed chunks it points to are cached for a year). The upside is that a fix to the nav bar or the table goes out to every app with one deploy, without opening a PR in every repo to bump a version. The obvious catch is that a broken deploy also reaches every app at once, which is why the remote has a stage deployment that the stage builds of all the apps load, and a change only goes to prod once it has sat there for a while.

Finding the remote

The usual way to point a host at a remote is a static string like shared_components@https://…/remoteEntry.js, which would mean one URL per environment and a rebuild to switch between them. What we do instead is use the other form webpack accepts there, a string that starts with promise followed by JavaScript that webpack puts in the bundle as-is and awaits at runtime. That code has to resolve with the remote’s container, which remoteEntry.js puts on window under the remote’s name.

A small helper in our shared dev utils generates that code, and this is a simplified version of it:

const remoteWithLocalFallback = ({ name, localPort, stageUrl, prodUrl, prodHosts }) => `promise (() => {
  const loadEntry = (url) => new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url + '/remoteEntry.js';
    script.onload = () => resolve(window.${name});
    script.onerror = reject;
    document.head.appendChild(script);
  });

  const isLocal = window.location.protocol === 'http:';
  const isProd = ${JSON.stringify(prodHosts)}.some((host) => window.location.host.includes(host));
  const deployed = isProd ? '${prodUrl}' : '${stageUrl}';

  return isLocal
    ? loadEntry('http://localhost:${localPort}').catch(() => loadEntry(deployed))
    : loadEntry(deployed);
})()`;

And each host uses it like this:

new ModuleFederationPlugin({
  name: 'office_app',
  filename: 'remoteEntry.js',
  remotes: {
    shared_components: remoteWithLocalFallback({
      name: 'shared_components',
      localPort: 3003,
      stageUrl: 'https://design-system.stage.example.com',
      prodUrl: 'https://design-system.example.com',
      prodHosts: ['office.example.com'],
    }),
  },
  shared: { /* … */ },
});

When the host runs on the dev server (plain http:), it first tries the components project on its local port, so if we’re working on a component we start both dev servers and the host picks up our local copy with hot reload and no config change, and if we’re not running it, the host falls through to stage, leaving one console error about the failed local load that everyone has learned to ignore. The deployed builds are all served over HTTPS, so they never try localhost and only pick stage or prod by looking at the page’s host (if you have an environment on plain http:, check something stricter than the protocol). The simplified loader also treats any successful script load as success, which means that if some other dev server answers on that port, the host gets undefined instead of falling back, and checking that window[name] is set in onload before resolving avoids that.

Since the promise string ends up in the bundle verbatim, everything interpolated into it has to be valid JavaScript, so a missing quote in a URL shows up as a syntax error in the host’s bundle and not in the webpack config, which takes a minute to figure out the first time.

Who gets to provide React

The hosts share React the normal way:

// in every host
shared: {
  ...deps,
  react: { singleton: true, requiredVersion: deps.react },
  'react-dom': { singleton: true, requiredVersion: deps['react-dom'] },
}

And the components remote does this:

// in the components remote
shared: {
  ...deps,
  react: { singleton: true, requiredVersion: '*', version: '0' },
  'react-dom': { singleton: true, requiredVersion: '*', version: '0' },
  'react-hook-form': { singleton: true, requiredVersion: '*', version: '0' },
  '@mui/x-date-pickers': { singleton: true, requiredVersion: '*', version: '0' },
  '@org/themes': { singleton: true, requiredVersion: '*', version: '99.99.99' },
}

To see why the remote’s numbers aren’t a typo, we need a bit of how sharing works at runtime. Every build that shares a module registers its own copy in the share scope under a version, which is the one from the dependency’s package.json unless version says otherwise. When something consumes a singleton, webpack picks the highest version in the scope, unless another copy has already been loaded, which it keeps, and if that version doesn’t satisfy the consumer’s requiredVersion, it logs a warning and uses it anyway.

So by registering its React as version 0, the remote makes sure its copy loses to any React a host brings, which means its components always render with the host’s React, and requiredVersion: '*' accepts whatever the host has, so there’s no warning either. When the components project runs on its own dev server its copy is the only one in the scope, so it’s used and everything works the same. We do the same for react-dom and for the libraries that keep state in React context, react-hook-form and the MUI date pickers, where a second copy means a component can’t see the provider the host rendered above it.

The themes package goes the other way, since with 99.99.99 the remote’s copy of @org/themes wins against any copy that hasn’t been loaded yet, so our components use the theme version they were built with. A host that imports the theme package itself (usually for its own ThemeProvider, before any remote component renders) has already loaded its copy by then, and webpack keeps a loaded singleton candidate even when a higher version is registered, so in that host our components get the host’s theme, while the host’s own imports keep their copy anyway, because they share it with a normal ^1.x range from package.json, which 99.99.99 doesn’t satisfy, and they aren’t singletons, so webpack just picks the highest copy that matches their range.

The nicer way to say “use the host’s React” would be leaving React out of the remote’s build completely, but then the components project can’t start on its own, and the fake version gives us both without a separate build. The only problem with it is that nothing in the config says why, which is why I keep explaining it, so if you copy this, put the reason in a comment next to it (we still haven’t).

The same components from npm

A couple of our projects can’t load the remote at runtime, a component library built with Vite that other apps install being one of them, so the components project is also published to our private npm registry as a normal package. The webpack build stays as it is, and the package is built separately with tsc into lib/, but the package.json that works for the remote is the wrong one to publish, since React, MUI and Emotion are regular dependencies there and would end up installed twice in every app that installs the package.

So publishing goes through npm’s prepack and postpack hooks, which run around npm pack (and npm publish, which packs first):

"scripts": {
  "prepack": "node ./scripts/preparePackage.js",
  "postpack": "node ./scripts/restorePackage.js"
}

preparePackage.js saves the original package.json as package.backup.json, then rewrites it for publishing:

const depsToMoveToPeerDependencies = ['@emotion/react', '@emotion/styled', '@mui/icons-material', '@mui/material', 'react', 'react-dom'];
const fieldsToRemove = ['devDependencies', 'scripts', 'overrides', 'resolutions', 'volta' /* ... */];

const { dependencies = {}, peerDependencies = {}, ...rest } = structuredClone(originalPackageJSON);

depsToMoveToPeerDependencies.forEach((dep) => {
  if (dependencies[dep]) {
    peerDependencies[dep] = dependencies[dep];
    delete dependencies[dep];
  }
});
fieldsToRemove.forEach((field) => delete rest[field]);

fs.writeFileSync('package.json', JSON.stringify({ ...rest, dependencies, peerDependencies }, null, '\t'));

Moving those to peerDependencies is the npm version of the version: '0' trick, telling the app installing the package to bring its own React and MUI. restorePackage.js puts the backup back afterwards, keeping the version field from the published file, so the working copy goes back to the remote’s package.json with the version that was released. But this only changes the package.json inside the tarball, since npm publish reads package.json from disk again after packing, by which time postpack has restored it, and that copy is what goes into the registry’s metadata, which is what package managers resolve from. So installs still see React and MUI as regular dependencies, and an app ends up with one copy only when its own ranges match and the package manager dedupes them. Publishing from a folder with its own rewritten package.json (semantic-release’s pkgRoot option, for example) would make the peer dependencies real.

Types

The last bit is TypeScript, since import('shared_components/Table') has no types out of the box. The remote generates declarations for its exposed files during the build and deploys them as an archive with the same deployment, and every host downloads and unpacks it before its own build.

Edit (2023-11-22): the types part grew into a post of its own, with the couple of odd files it needs and a webpack cache gotcha.


Keeping the design in an MUI theme means designers and developers change the same files and apps get the result without touching their components. On the delivery side, loading the remote through a promise with a local fallback makes working on a component and an app at the same time painless, and the version value in a shared entry decides whose copy of a library wins, a low fake version to defer to the host and a high one to prefer your own (unless the host has already loaded its copy). Whichever number you use, put a comment next to it saying what it’s for.

Email address copied [email protected]