You Might Not Need Module Federation: Orchestrate your Microfrontends at Runtime with Import Maps
Tags: javascript, webdev, webcomponents, microfrontends
Published: 2023-01-05 15:43:06

## TL;DR

Managing microfrontends in a complex feature-rich app can become a tedious task and easily turn it into a Frankenstein's monster when there's no clear strategy involved. 

Using third-party tools like Webpack Module Federation helps to streamline the building and loading of microfrontends, but leads to vendor lock-in, which can be a problem.

Import Maps can be seen as a web native alternative to Webpack Module Federation to manage microfrontends at runtime. In this article, we will:

- Explore the concept of Import Maps
- Build a demo app
- Summarise the pros & cons


## Import Maps in a nutshell

The concept of Import Maps was born in [2018](https://github.com/WICG/import-maps/commit/2ed3a0c6acb196d2469cbb5e0fc064276d0fe5dc) and made its long way until it was declared a [new web standard](https://html.spec.whatwg.org/multipage/webappapis.html#import-maps) implemented by Chrome in [2021](https://chromestatus.com/feature/5315286962012160) and some [other browsers](https://caniuse.com/?search=importmap).

Import Maps let you define a JSON where the keys are ES module names and the values are versioned/digested file paths, for example: 

```tsx
<script type="importmap">
  {
    "imports": {
      "my-component": "https://assets.mycompany.io/scripts/my-component/index.5475c608.js"
    }
  }
</script>
```

Such mapping can be resolved directly in the browser, so you can build apps with ES modules without the need for transpiling or bundling. This frees you from needing Vite, Webpack, npm, or similar.

Import maps allow us to write:

```tsx
import 'my-component';
```

instead of the following:

```tsx
import 'https://assets.mycompany.io/scripts/my-component/index.5475c608.js';
```

and let the browser resolve the actual path at runtime.

## Advanced Import Maps features

You can reuse an import specifier (for example `lodash` below) to refer to different versions of the same library by using scopes. This allows you to change the meaning of an import within that given scope. As a result, any module in the `https://assets.mycompany.io/scripts/my-components` path will be using `lodash-es` version `3.9.3` while all other modules will use version `4.17.21`.

```jsx
<script type="importmap">
  {
    "imports": {
      "my-component": "https://assets.mycompany.io/scripts/my-component/index.5475c608.js",
      // allows import { my-component } from "component-library" syntax
      "component-library/": "https://assets.mycompany.io/scripts/my-components/",
      "lodash": "https://esm.sh/lodash-es@4.17.21", ⬅
      "lazyload": "IntersectionObserver" in window ? "./lazyload.js" : "./lazyload-fallback.js",
    },
    "scopes": {
      "https://assets.mycompany.io/scripts/my-components/": {
        "lodash": "https://esm.sh/lodash-es@3.9.3" ⬅
      }
    }
  }
</script>

```

You can also construct an import map dynamically based on conditions: the example above taken from [this article](https://www.honeybadger.io/blog/import-maps/) shows how you can load different modules based on the support of `IntersectionObserver` API.

## Demo app

In this article, we bring the idea of Import Maps further by placing an Import Map between the host app and microfrontends and applying the dependency inversion principle. This makes the host app not directly dependent on a concrete microfrontend version or its location, but rather on its abstraction via name or alias.

We are going to build an online store that has only one, but highly customizable assortment type: T-shirt.

### Step 1: Outline the Architecture

There is an arbitrary number of microfrontends that are assigned to the development teams, each of them is free to choose the tech stack, build and CI/CD tools. The “only” constraint is to make sure each build pipeline produces 3 artefacts: **ESM bundle**, **Manifest** and other **Static Assets**.

The lightweight [Nest.js](https://nestjs.com/) **Import Map Resolver** server has two main roles: store and update the importmap, but also handle the submission of JS assets. [Single-spa](https://single-spa.js.org/) has a similar solution [available](https://github.com/single-spa/import-map-deployer).

The **Publisher** will read your Manifest, extract the bundle filename as well as externalized dependencies and publish them to the **Import Map Resolver**.

The **Assets Server** is used as a Web-enabled storage to host JS assets. To store images, videos, and other assets we can choose an arbitrary **Storage,** for example, an [Amazon S3](https://aws.amazon.com/s3) bucket. **CDN** is used to serve third-party libs and frameworks as ES modules, a good one is [ESM.sh](https://esm.sh/).

![Architecture diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/erdhv9elspy5npx66e32.png)

**ESM bundle**

Your production-ready application [ESM bundle](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) is generated by Webpack, Vite, Rollup or any other bundler of your choice. For simplicity of the setup, [CSS Injected By JS](https://www.npmjs.com/package/vite-plugin-css-injected-by-js) plugin for Vite is used along with the [scoped styles](https://css-tricks.com/saving-the-day-with-scoped-css/) to build a single ES module with injected CSS.

If your build produces more than one bundle (for example, due to [code splitting](https://webpack.js.org/guides/code-splitting/)), you have two options:

- concatenate them after the build, for example via [concat](https://www.npmjs.com/package/concat)
- alter the **Publisher** to loop over the multiple entry chunks and add the prefix, e.g.: `my-component:main`, `my-component:polyfill`, and so on.

**Manifest**

This is a JSON file that contains the mapping of non-hashed asset filenames to their hashed versions and, if you are using Vite, you just need to add `manifest: true` to your [Vite config](https://vitejs.dev/config/build-options.html#build-manifest). This will produce the following file in the `/dist` of your project:

```jsx
{
  "main.js": {
    "file": "assets/index.fb458d74.js",
    "isEntry": true
  },
  "views/cart.js": {
    "file": "assets/foo.869aea0d.js"
  }
}
```

The generated Manifest will be used by the **Publisher** to know the mapping of your microfrontend unique name to its ESM bundle.

**Static assets**

Everything else, such as images, videos and other static files required by your microfrontend.

### Step 2: Define the UI and split into microfrontends

Our online store demo app will have three views: Home, Product & Cart:

![T-Shop UI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1xpzff1mph7hgt4l2j11.png)

Vue is used as a core “metaframework” (simply stated, a framework of frameworks) to have out-of-the-box routing, simple state management with [Pinia](https://pinia.vuejs.org/) and [Vite](https://vitejs.dev/) as a bundler. It is not necessary at all to use the “metaframework”, moreover, during the build, you’ll get errors from Vite's internal [import-analysis plugin](https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/importAnalysis.ts) because of unresolved imports (good news, there is a solution for that, see “Challenges → Metaframework”).

![T-Shop Wireframes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aitfgt9z4416purxmh31.png)

To demonstrate how several microfrontends can co-exist together on the same page, they are built with four different frameworks. To make each app's  setup look similar, [Vite template presets](https://vitejs.dev/guide/#trying-vite-online) are used to generate Vue, React, Lit and Svelte microfrontends that are compiled into [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components).  You may consider splitting your app by functional area and building your microfrontends around business domains, such as Order, Product, etc.

![T-Shop Microfrontends](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kli7s8c32wqt6lylxp2w.png)

### Step 3: Build the app

The full source of the Demo app can be found on [Github](https://github.com/zaikinv/t-shop).



## Common problems & solutions

**Take control away from the bundler when resolving imports**

How do bundlers work? If you ignore the implementation details and go to the highest level of abstraction, they concatenate all the jungle of JS modules and put them into one big chunk, that is minified, uglified, and [tree-shaked](https://webpack.js.org/guides/tree-shaking/) to get rid of unused code. Simple concatenation wouldn’t work. You need to indicate the entry point and make sure you don’t have modules that import themselves - cyclic dependencies. Most of the bundlers solve this by building an abstract syntax tree. For example, Rollup does it with [Acorn](https://survivejs.com/blog/rollup-interview/#how-does-rollup-work-).

![Module Resolution](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0niw5yr8vqhjrxe71f5l.png)

Using micro-frontends resolved via Import Maps introduces a challenge for your bundler that should normally know your dependencies at **compile time**, not at **runtime**. We need to tell Rollup to stop building the tree once a dependency from the Import Map is met and make the current module a leaf node.

Luckily, Vite, Rollup and Webpack have options to take control away from the bundler and let the browser resolve the specified imports by providing their names in the [configuration](https://rollupjs.org/guide/en/#external).

```jsx
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    rollupOptions: {
      external: [
        "widget",
        "some-other-widget",
        "lodash"
      ],
    },
  },
});
```

**Load import map dynamically**

[Specs](https://github.com/WICG/import-maps#installation) say that “any import maps must be present and successfully fetched before any module resolution is done”. Essentially, it means that the importmap must be inserted in the DOM earlier than any other async script.

Vite is internally using [build-html](https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/html.ts#L298) plugin, that produces `index.html` with the entry point added via `<script type="module" src="bundle.js>` tag to the `<head>` section. This is not what we want. Instead, we would like to execute a script that will fetch the import map first, add it to the page, and then load the app script.

To build a custom `index.html` the [Async Import Map plugin](https://github.com/zaikinv/t-shop/blob/master/shell/vite.config.js#L10) for Vite was created that is internally using [Rollup Plugin HTML](https://www.npmjs.com/package/@rollup/plugin-html). The plugin extracts the entry point script from the list of generated assets (by lookup for `isEntry: true`), stashes it, loads the import map from the specified URL and then unstashes and appends the entry point script, giving control back to your app.

See full source on [Github](https://github.com/zaikinv/t-shop/blob/master/shell/plugins/asyncImportMap.js).

**Shared state and communication**

Eventually, there are only 6 ways to share the state across microfrontends:

- **Windowed Observable** uses the global `window` object as the medium to share the data, often wrapped into a [pub-sub](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) library
- **Web storage**, such as Local Storage, Session Storage or Cookies
- **URL** via query / params
- **In-memory** (e.g. [Redux](https://redux.js.org/))
- **Backend** (session or persisted state)
- **Props and Custom events / Callbacks**

Everything else you may come across could be just an abstraction on top of these methods. [Here](https://dev.to/luistak/cross-micro-frontends-communication-30m3) is a good summary of their pros and cons.

Since the goal is to use as many native web capabilities and avoid vendor lock-in, we can stick to Props & Custom Events. One important note to mention: to let an event “escape” from the Shadow DOM, we need to set `bubbles: true` and `composed: true`. This way we make sure events propagate through the parent-child as well as the shadow tree hierarchy. A nice explanation can be found in the [blogpost](https://pm.dartus.fr/blog/a-complete-guide-on-shadow-dom-and-event-propagation/).

```jsx
document.dispatchEvent(
  new CustomEvent("select-color", {
    bubbles: true,
    composed: true,
    detail: 'blue',
  })
);
```

**Shared dependencies**

To share your microfrontend dependencies, you can declare them as “external” by providing them in the [configuration](https://rollupjs.org/guide/en/#external) as follows:

```jsx
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    rollupOptions: {
      external: ["react", "react-dom", "react-to-webcomponent"],
      output: {
        globals: {
          react: "react",
          reactDom: "react-dom",
          reactToWebComponent: "react-to-webcomponent",
        },
      },
    },
  },
});
```

Here we are telling Rollup to not bundle React dependencies as well as to provide global variables for them.

But how do we deal with dependency mismatches when one or more microfrontends are using the same lib, but with different versions? Let’s say Footer and Header are two React major versions apart. As mentioned before, we can use [scopes](https://github.com/WICG/import-maps#multiple-versions-of-the-same-module):

```jsx
<script type="importmap">
  {
    "imports": {
      "header": "/path/to/header/index.5475c608.js",
      "footer": "/path/to/footer/index.6087f008.js",
      "react": "https://esm.sh/react"
    },
    "scopes": {
      "/path/to/header/": {
        "react": "https://esm.sh/react@16.13.1"
      },
      "/path/to/footer/": {
        "react": "https://esm.sh/react@18.2.0"
      }
    }
  }
</script>
```

Alternatively, we can provide different import specifiers:

```jsx
<script type="importmap">
  {
    "imports": {
      "header": "/path/to/header/index.5475c608.js",
      "footer": "/path/to/footer/index.6087f008.js",
      "react@16": "https://esm.sh/react@16.13.1",
      "react@18": "https://esm.sh/react@18.2.0",
    }
  }
</script>
```

If you need some sophisticated logic to build your import map, **Import Map Resolver** is the place to put it. Let’s say one of your microfrontends publishes its new version that uses `react@17.0.1`, but you already have `react@17.0.0` in your importmap. In this case, the **Import Map Resolver** would remove an older version and replace it with the newest one. It is one minor version ahead, assuming backward compatibility is guaranteed.

**Library microfrontend**

Microfrontends can be published as a Custom Components library.

Example using Vite and Svelte:

```jsx
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';

export default defineConfig({
  build: {
    rollupOptions: {
      input: [
        './src/Header.svelte',
        './src/Footer.svelte'
      ],
    }
  },
  plugins: [
    svelte({
      compilerOptions: {
        customElement: true,
      },
    })
  ]
});
```

This will produce two separate chunks, one for the `Header` and one for the `Footer`. Vite supports [library Mode](https://vitejs.dev/guide/build.html#library-mode) for Vue and other frameworks.

Without going into each library configuration details, the general principle is to alter your `main.ts` entry point (or each of your entry points if they are many) in a way you’d like to expose your microfrontend defined as a Custom Element.

```jsx
import MyComponent from '.src/my-component';

customElements.define("my-component", componentWrapperFn(MyComponent));
```

where `componentWrapperFn` is a function provided by your (or a third-party) library that returns a custom element [constructor](https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define) that extends `HTMLElement`. It could be native `defineCustomElement` in the case of [Vue](https://vuejs.org/guide/extras/web-components.html#building-custom-elements-with-vue) or third-party `reactToWebComponent` from [react-to-webcomponent](https://www.npmjs.com/package/react-to-webcomponent). A blogpost on [webcomponents.dev](https://webcomponents.dev/blog/all-the-ways-to-make-a-web-component/) and also [webcomponents.dev](https://webcomponents.dev/docs/) docs provide a great summary of how to build Web Components with different libraries and frameworks.

**Metaframework**

As mentioned in the section [Demo app](#demo-app), a metaframework is used to glue the microfrontends together. Choosing no framework is also a valid option. Import Maps perfectly support this case by resolving imports directly in the browser. The choice of using Vue is mainly to avoid writing boilerplate code for routing and make the container components lean, having little to no low-level DOM manipulation. There is a good [article](https://khalilstemmler.com/articles/client-side-architecture/layers/#Container-components-are-pages) explaining why we need the container components and how to structure them.

**Routing**

Routing between container components/pages is covered by the metaframework in case you are using one. If not, you can opt for [Navigo](https://github.com/krasimir/navigo) as a simple dependency-free JS router.

In rare cases, when you need navigation within individual microfrontends this is where it gets tricky: at the end, you only have one address bar. You can map the flattened structure of your compound URL state (for example, map `https://my-app.com/mfe-1:article/search` and  `https://my-app.com/mfe-3:invoice/edit/8` to `https://my-app.com/(mfe-1:article/search//mfe-2:invoice/edit/8)`) to enable two-level routing with the help of your framework. There is a [library](https://www.npmjs.com/package/@angular-architects/microapp) for Angular that uses [URL Serializer](https://angular.io/api/router/UrlSerializer) to intercept and manipulate browser URLs.

That being said, this approach also introduces an unwanted tight coupling among microfrontends: the host app shouldn’t know the details of individual microfrontends routing. When a team needs to change or add a new URL, the host app would need to be adjusted and redeployed. Instead, try avoiding two-level routing at the stage of application design. To better understand all the consequences of this approach, you may want to read the book [Micro Frontends in Action](https://www.manning.com/books/micro-frontends-in-action) by Michael Geers, chapter “App shell with two-level routing”.

## Pros

Let’s summarize all the benefits that Import Maps offer:

- flexibility for microfrontend teams (each team can have its own tech stack, CI/CD, coding guidelines, infrastructure: everything before final artefacts are built)
- easy step-by-step migration of existing codebases by replacing components or entire pages with microfrontends
- the host app is lean and detached from the development of microfrontends and focuses on the composition of pages, providing the data and handling events
- the host app is not aware neither of the existence nor the implementation details of your microfrontends: the only “contract” is the API of your microfrontend (props/events)
- import map entries are lazy-loaded: no JS is downloaded before you actually `import()`
- you may not need any build tools at all: import maps work in the browser at runtime
- it takes seconds to update your app (by changing entry in the import map)
- it takes seconds to rollback

## Cons

Let’s summarize all the drawbacks that the usage of Import Maps brings:

- import Maps are [not supported](https://caniuse.com/import-maps) in some browsers, however, there are [polyfills](https://github.com/WICG/import-maps#community-polyfills-and-tooling)
- the overall amount of bytes downloaded when using microfrontends in comparison to monolith is unavoidably higher. Even though you can externalize and share your app dependencies, you cannot avoid eventual code duplication in individual microfrontends
- not suitable for small and medium size projects where single core framework would be a better fit

## Conclusion

Using Module Federation in comparison to Import Maps has a major drawback, which is vendor lock-in, that makes your product dependent on another product: Webpack. All your micro-frontends as well as your host app must comply with it and be on the correct version. You also cannot avoid the compilation step, while Import Maps can be used directly in the browser.

At the same time, new [web standards](https://html.spec.whatwg.org/multipage/webappapis.html#import-maps) are emerging and replacing the need for third-party products. While the standard is being developed further, getting new features, such as [multiple import map support](https://github.com/WICG/import-maps#multiple-import-map-support) and [programmatic API](https://github.com/WICG/import-maps#programmatic-api), you can already start using them now with the help of [ES Module Shims](https://github.com/guybedford/es-module-shims) or [System JS](https://github.com/systemjs/systemjs#import-maps).

See full source of the Demo app on [Github](https://github.com/zaikinv/t-shop).