Socket
Book a DemoInstallSign in
Socket

@epam/microfrontends

Package Overview
Dependencies
Maintainers
6
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@epam/microfrontends

Provides a set of helpers and CLI tools to facilitate development of micro-frontend widgets.

latest
npmnpm
Version
1.1.1
Version published
Weekly downloads
354
-13.87%
Maintainers
6
Weekly downloads
 
Created
Source

@epam/microfrontends

This package contains utilities and scripts that simplify the development of micro-frontends.

Definitions

  • Remote app: The application that hosts remote widgets.
  • Host app: The application that renders remote widgets.
  • Remote facade (widgets.js): The unified interface hosted on the "Remote app" and used by the "Host app" to render remote widgets.

Main Idea

The "Host app" retrieves remote widgets from the "Remote app" using the "Remote facade," which is located at a well-known URL.

This is better described by example.
Let's assume that the Remote app is hosted on this origin: http://127.0.0.1:4000
The host assumes that the Remote facade is located at a well-known URL, which looks like this: http://127.0.0.1:4000/widgets.js
There are several other resources hosted by the "Remote app," and the "Host" doesn't know about the presence of such resources. However, they are used implicitly (by widgets.js) during the mounting of the remote widgets. Here is the list of resources:

  • Remote Assets Manifest (http://127.0.0.1:4000/<path_to_build_manifest>)
  • Remote App JS bundle (http://127.0.0.1:4000/<path_to_main_js_bundle>)
  • Remote App CSS bundle (http://127.0.0.1:4000/<path_to_main_css_bundle>)

Below is the sequence of actions performed by the Host to mount a remote widget.

  • LOAD
    // The "Remote facade" is loaded using a well-known URL. Internally, the Host loads the widget like this.
    const remote = await import('http://127.0.0.1:4000/widgets.js');
    
  • INIT
    /**
    * Several IMPLICIT actions are done during the init(). The Host doesn't know anything about these actions; they are encapsulated inside "widgets.js".
    * 1) The "Remote Assets Manifest" file is loaded (if applicable).
    * 2) The URL to the "Remote App JS bundle" is determined from the manifest (if applicable).
    * 3) The URL to the "Remote App CSS bundle" is determined from the manifest (if applicable).
    * 4) The window.Widgets global variable is created (unless already defined). It acts as a simple registry that helps to define/require widgets.
    * 5) The "Remote App JS bundle" is loaded via window.Widgets.require(/../). Note: A "script" tag is used under the hood to load the JS bundle. It's loaded only once and cached.
    * 6) Widgets defined during the load (via window.Widgets.define(...)) are collected.
    * Note: The "Remote App CSS bundle" is NOT loaded at this step. It will be loaded later, during the widget "mount".
    */
    const widgets = await remote.default.init();
    
  • MOUNT
    // The "Remote App CSS bundle" is loaded as part of this call (right before the actual mount occurs).
    const { unmount } = widgets['demoWidget'].mount(/*...*/);
    
  • UNMOUNT
    // The "Remote App CSS bundle" is unloaded after this step.
    unmount();
    

Known issues

See KNOWN_ISSUES.md

Features of the "Remote facade" (widgets.js)

  • Possibility to customize mount (see CLI usage example for details)
  • Provides a Widgets module system that supports loading bundles in the popular formats (IIFE, ESM)
  • Processed with Babel to guarantee compatibility with browsers
  • Error handling
  • Corner cases handling
  • Encapsulates the logic of parsing different types of asset manifest files
  • It is hosted only on the remote side because it contains logic specific to the remote app

CLI Usage

(Remote app) Generate Remote Facade (widgets.js)

Run the command below from the remote project's root folder. It creates "Remote facade" files and puts them in the ./public folder.
NOTE: It needs to be run the very first time and can only be run again when the @epam/microfrontends package version has changed.

# 1) Without installing the NPM package, this is preferable. Exact version can be specified instead of "latest".
npx --yes @epam/microfrontends@latest epam-microfrontends-init --app-type=webpack

# 2) When "@epam/microfrontends" is installed locally.
npx epam-microfrontends-init --app-type=webpack

The following files will be created:

  • widgets.js (+ widgets.js.map) - The minified version of the "Remote facade" hosted on the remote side. The "Host app" downloads and runs this file to retrieve remote widgets.
  • widgets.dev.js and widgets-dev.html - The non-minified version of the "Remote facade". It might be used as a starting point to test remote widgets locally in isolation.
    NOTE: It's safe to remove these files unless you plan to locally test your widgets via "widgets-dev.html".

All options:

--app-type (required)  Application type (in all cases the widget.js/widgets-dev.html will be copied to "./public" dir)  
        webpack - for Webpack apps
        vite - for Vite apps
        angular - for Angular apps
--bundle-format (optional)  The format of the app bundle which contains single Widgets.define(...):
        iife - when bundle is IIFE (this is a default value for --app-type=webpack
        esm - when bundle is ESM (this is a default value for --app-type=vite and --app-type=angular)
--remote-css (optional)
        shadowRoot (this is a default value for --app-type=webpack and --app-type=vite) - the CSS will be added to the shadow root of the target element 
        global - the CSS will be added to the document.head of the host page.
        skip - (this is a default value for --app-type=angular) CSS will be loaded as part of mount method of the remote widget.
--add-css-to-host (optional)
        {path} - path to the css on remote widget's server. It will be injected into the host page when the widget mounts. E.g.: /app/app_name/host/styles.css
--reset-css-in-shadow-dom (optional)
        {boolean} - when true (it is by default), it adds inline style which resets CSS in ShadowRoot

(Angular app-specific) Generate asset-manifest.json

# Run next CLI command AFTER every Angular build. This command will generate asset-manifest based on the Angular build output (directory "./dist")
npx --yes @epam/microfrontends@latest epam-microfrontends-init --cmd=angular

React

Define remote widgets

import { createRoot } from 'react-dom/client';
import { IHistoryMicroFe } from '@epam/microfrontends/helpers/history';
const demoWidget = {
    mount: (target: HTMLElement, params: any) => {
        /*
         * If a remote widget uses routing, then it's necessary to do all routing via the "params.historyMicroFe".
         * Use "params.historyMicroFe" directly or via converters exported from "@epam/microfrontends/helpers/history"
         */
        const root = createRoot(target);
        root.render(<DemoWidgetComponent />);
        return {
            unmount: () => {
                root.unmount();
            }
        }
    }
};
if (isPartOfTheNormalApp) {
    // render app
}
(window as any).Widgets?.define(() => ({
    demoWidget,
}));

(Host) Consume the remote widgets

import { RemoteWidget, RemoteWidgetContext } from '@epam/microfrontends/helpers/react';
import { IHistory4Full_to_IHistoryMicroFe } from '@epam/microfrontends/helpers/history';
import { createBrowserHistory } from 'history';
//...//
const history = createBrowserHistory();
const historyMicroFe = IHistory4Full_to_IHistoryMicroFe(history as any);
//...//
function App() {
    // Somewhere in the app:
    const params = { historyMicroFe };
    return (
        <RemoteWidgetContext.Provider value={params}>
            <RemoteWidget
                url="http://172.20.0.1:4001/widgets.js"
                name="demoWidget"
            />
            <RemoteWidget
                url="http://172.20.0.1:4002/widgets.js"
                name="demoWidget"
            />
        </>
    )
}

Angular

(Remote) Define remote widgets

// 1. Add widget component
@Component({
    selector: `demoWidget-root`,
    standalone: true,
    templateUrl: "./demoWidget.component.html",
    encapsulation: ViewEncapsulation.ShadowDom,
})
export class DemoWidgetComponent {
    title = "angular";
}

// 2. Register remote widget
(window as any).Widgets?.define(() => ({
    demoWidget: {
        mount: (targetElement: HTMLElement, props: Record<string, any>) => {
            targetElement.appendChild(document.createElement(`demoWidget-root`));
            bootstrapApplication(AppComponent, {
                providers: [{ provide: YOUR_TOKEN, useValue: props.yourValue }] }
            ).catch((err) => console.error(err));
            return { unmount: () => {} };
        }
    },
}));

(Host) Consume the remote widgets

import { RemoteWidgetComponent } from '@epam/microfrontends/helpers/angular17';
//...//
@Component({
    selector: 'mfe-demo',
    standalone: true,
    imports: [RemoteWidgetComponent],
    template: '<mfe-angular [url]="url" [widgetName]="widgetName" [props]="props"></mfe-angular>',
})
export class AppComponent {
    public url = `http://localhost:4004/apps/remotes-angular/widgets.js`;
    public widgetName = 'demoWidget';
    public props = { yourValue: { id: '1', name: 'Input for mfe Angular' } };
}

Routing in remote widgets

Strictly speaking, this library does not impose any restrictions on how routing should be implemented, either in the remote or in the host. This section just contains recommendations that could be useful in most typical cases.

If some remote widget uses routing, then it's expected that it should use "historyMicroFe" standard interface which is provided by the "Host app". In general case, host and remote could use different routers, e.g.:
(HOST: unknown 1) ---> (IHistoryMicroFe) --> (REMOTE: unknown 2)

In such situation, some adapters will be required:

  • unknown 1 -> IHistoryMicroFe
  • IHistoryMicroFe -> unknown 2

There are several adapters available OOTB in this package. They cover some typical uses cases:

  • IHistory4Full_to_IHistoryMicroFe
  • IRouter6_to_IHistoryMicroFe
  • IHistoryMicroFe_to_IHistoryRouter6
  • IHistoryMicroFe_to_IHistory4Full

Usage of "basename"

  • It's expected that "Host app" doesn't use "basename" feature of router. So that full location path is exposed to "Remote app".
  • The "Remote app" may optionally use "basename" for its routing if needed. See the example here: packages/examples/remotes/cra-router5/src/widgets/demoWidget/demoWidget.tsx

FAQs

Package last updated on 26 Sep 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts