Moonlit Torii

Micro Frontends (Wujie)

Original source organized into a complete guide to micro-frontend approaches, Web Components, pnpm monorepos, Wujie integration, preloading, communication, and Module Federation.

Original: Xiaoman zs, “Micro Frontends (Wujie)”

Micro Frontends (Wujie) 2023-03-20 47,447 10-minute read This article is participating in the “Gold and Stone Program.”

Preface: Micro frontends are already a mature field, yet every existing approach has problems—or offers no support at all—for core needs such as adaptation cost, style isolation, runtime performance, blank screens, child-app communication, child-app keep-alive, activating multiple apps, Vite support, and application sharing. This article introduces a new iframe-based micro-frontend approach that addresses these core requirements.

Micro-frontend concept

Micro frontends borrow the idea of microservices and split a large application into multiple independent, flexible small applications. Each application can be developed, run, and deployed independently, and they can be combined freely. This reduces coupling and makes the system more flexible.

Micro-frontend characteristics

Technology-stack independent: the host framework does not restrict the stack of connected applications, so each child can choose Vue, React, jQuery, Angular, or another stack. Independent development and deployment: teams use separate repositories and deployments without depending on one another. Incremental upgrades: once an application becomes large, upgrades and refactoring are difficult; micro-applications support gradual migration. Independent runtimes: micro-applications do not depend on one another at runtime and have independent state management.

Scenario demonstration

Admin system The outermost layer can act as the host application and contain different child applications without restricting their technologies.

Original figure 1

Web store (a future trend) For example, navigation sites could offer micro-frontend integration. Our site could join the platform and call APIs that enable richer interactions, similar to mini programs. Just as mini programs can use WeChat capabilities such as payments and QR scanning, a navigation platform could expose APIs to integrated sites and enable more interesting experiences.

Original figure 2

Micro-frontend approaches

iframe approach

Advantages

Relatively simple integration Stable and thorough isolation Limitations

The DOM feels strongly separated; dialogs are confined to the iframe, which may also have scrollbars. Communication is cumbersome, and refreshing loses the iframe URL state. Browser back and forward buttons do not work as expected.

qiankun approach

qiankun is a micro-frontend approach based on single-spa.

Advantages

Loading child applications through HTML Entry greatly reduces adaptation work compared with JS Entry. It provides a complete sandbox: SnapshotSandbox, LegacySandbox, and ProxySandbox progressively enhance JavaScript isolation, while strictStyleIsolation and experimentalStyleIsolation cover different CSS-isolation scenarios. It supports static-resource preloading. Limitations

Adaptation cost is relatively high because engineering setup, lifecycles, static-resource paths, and routing all require changes. Strict CSS isolation can cause various problems, while the JavaScript sandbox can significantly reduce performance in some scenarios. It cannot activate multiple child applications simultaneously and does not support child-app keep-alive. It cannot run ES module scripts from tools such as Vite. Under the hood, the JavaScript sandbox takes a snapshot through a proxy and wraps code in with(window) {}. The window inside the block is actually proxy.window; declaring var name = 'xiaoman' attaches the variable to proxy.window, not the real window. CSS isolation uses either Shadow DOM or a Vue scoped-style-like selector such as [data-qiankun-426732].

micro-app approach

micro-app is a micro-frontend approach based on Web Components and the qiankun sandbox.

Advantages

Using Web Components to load child applications is more elegant than single-spa-style registration and listeners. Reusing qiankun's sandbox, which has been verified by many projects, makes the framework more reliable. Its component-style API better matches common usage and supports child-app keep-alive. It reduces child-application adaptation cost and supports static-resource preloading. Limitations

Integration costs less than qiankun, but routing still has dependencies. (Virtual routing has addressed this.) After activating multiple applications, their route states cannot be preserved and are lost on refresh. (Virtual routing has addressed this.) The CSS sandbox still cannot provide absolute isolation; the JavaScript sandbox caches global-variable lookups to improve performance. It supports Vite, but a plugin must adapt the child application, and JavaScript code cannot be sandboxed. It provides no fallback for browsers without Web Components support. Its JavaScript isolation resembles qiankun and uses proxy + with; CSS isolation adds a custom prefix similar to scoped styles.

javascript
const prefix = `micro-app[name=${appName}]`

Original figure 3

EMP approach

EMP is a micro-frontend approach based on Webpack 5 Module Federation.

Advantages

Webpack federation can decouple the dependencies of all child applications. Applications can call one another and share modules in a decentralized way. Remote modules support TypeScript. Limitations

It depends heavily on Webpack and is unfriendly to legacy projects. It has no effective CSS or JavaScript sandbox and relies on developer discipline. Child-app keep-alive and simultaneous multi-app activation are unavailable. Host and child routes may conflict. Under the hood, this resembles bundle splitting and can also be called module sharing. For example, a React module can be shared with a Vue project, or a Vue 2 component with Vue 3.

Wujie micro-frontend approach

Try the Wujie Vue demo

Advantages

Simple integration requiring only four or five lines of code No extra handling for Vite Preloading Application keep-alive mechanism Limitations

JavaScript is isolated in an empty iframe. Axios in the child application must be adapted manually. The iframe sandbox sets src to the host application's host. During initialization it waits for the iframe's location.origin to change from about:blank to the host origin; using a timer for this wait is not very elegant. Under the hood, Shadow DOM isolates CSS, an empty iframe isolates JavaScript, and a proxy handles communication.

Partial source: juejin.cn/post/712564…

Prerequisite: understanding Web Components

Demonstrating Web Components syntax, property passing, and style isolation

typescript
window.onload = () => {
    class WuJie extends HTMLElement {
        constructor() {
            super()
            this.init()
            this.getAttr('url')
        }
        init() {
          const shadow =  this.attachShadow({ mode: "open" }) // Enable Shadow DOM for style isolation
          const template = document.querySelector('#wu-jie') as HTMLTemplateElement
          console.log(template);
          
          shadow.appendChild(template.content.cloneNode(true))
        }
        getAttr (str:string) {
           console.log('Get attribute',this.getAttribute(str));
           
        }

        // Lifecycle: triggered automatically when inserted
        connectedCallback () {
           console.log('Similar to Vue mounted');
        }
        // Lifecycle: unmount
        disconnectedCallback () {
              console.log('Similar to Vue destroyed');
        }
        // Similar to watch
        attributeChangedCallback (name:any, oldVal:any, newVal:any) {
            console.log('Similar to Vue watch; triggered automatically when an attribute changes');
        }

    }
    
    window.customElements.define('wu-jie', WuJie)
}
html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./index.js"></script>
</head>

<body>
    <!-- Add an outer div to test isolation -->
    <div>I am a div</div>

    <wu-jie url="xxxxxx"></wu-jie>


    <template id="wu-jie">
       <!-- The div style applies globally outside Shadow DOM -->
        <style>
            div {
                background: red;
            }
        </style>
         <div>
            Xiaoman zs (testing style isolation)
         </div>
    </template>
</body>

</html>

CSS styles can be isolated completely.

Original figure 4

Prerequisite 2: monorepo architecture

Our micro-frontend system has one host and multiple child applications. Installing dependencies in every application separately would be inefficient, so we use a monorepo and complete installation in one pass.

The first step is to install pnpm.

pnpm has built-in support for multiple packages in one repository, making it an excellent choice for a monorepo.

bash
npm i pnpm -g

Create main at the outer level as the host, then create a web folder containing Vue and React child applications.

Original figure 5

Configure the monorepo

Create pnpm-workspace.yaml at the repository root to configure workspace packages.

yaml
packages:
  # all packages in direct subdirs of packages/
  - 'main'
  # all packages in subdirs of components/
  - 'web/**'

After configuration, run install once.

It hoists shared dependencies to the outer layer while leaving only essential dependencies inside each package.

Getting started with Wujie

We use Vue 3 as the host application. First install the dependencies.

bash
vue2 npm i wujie-vue2 -S

vue3 npm i wujie-vue3 -S

react npm i wujie-react -S

The host application's main.ts

typescript
import { createApp } from 'vue'
import App from './App.vue'
import Wujie from 'wujie-vue3'
createApp(App).use(Wujie).mount('#app')

In the host's HelloWorld component, set url to the child application's URL. Start the child with npm run dev.

vue
<template>
  <div>
    <WujieVue width="100%" height="100%" name="xxx" :url="url" ></WujieVue>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive } from 'vue'
const url = 'http://127.0.0.1:5174/'
</script>

<style scoped lang='less'></style>

Only a few lines of code are needed to create the micro-frontend application, so integration cost is low.

Original figure 6

How wujie-vue3 works

This package is a wrapper built by the author around Wujie, and we can build our own wrapper as well.

Documentation

Configure a child application

This is optional. Because preloadApp and startApp repeat parameters, setupApp can define defaults and avoid repeated input.

JavaScript

javascript
setupApp({ name: "unique-id", url: "child-app-url", exec: true, el: "container", sync: true })

Preload

JavaScript

javascript
preloadApp({ name: "unique-id"});

Start a child application

JavaScript

javascript
startApp({ name: "unique-id" });

Once these APIs are understood, we can wrap a Wujie component. Here we use Vue 3, Webpack, and SWC.

Dependencies

json
    "@swc/core": "^1.3.42",
    "swc-loader": "^0.2.3",
    "ts-loader": "^9.4.2",
    "typescript": "^5.0.2",
    "vue": "^3.2.47",
    "webpack": "^5.77.0",
    "webpack-cli": "^5.0.1",
    "wujie": "^1.0.13"

1. Webpack configuration

javascript
const { Configuration } = require('webpack')
const path = require('path')

/**
 * @type {Configuration} // Enable configuration IntelliSense
 */
const config = {
    entry: "./src/index.ts",
    output: {
        filename: "wujie.js",
        path:path.resolve(__dirname, './lib') ,
        library:"Wujie",
        libraryTarget:"umd",
        umdNamedDefine:true
    },
    externals:{
      vue:'vue',
      wujie:"wujie"
    },
    mode:"none",
    cache:true,
    module: {
        rules: [
            {
                test: /\.ts$/,  // Parse TypeScript
                loader: "swc-loader", // Use swc-loader
            }
        ]
    },

}

module.exports = config

Original figure 7

Original figure 8

This shows the difference. Why use SWC? SWC is written in Rust and runs several times faster than native alternatives; its website states that it is twenty times faster than Babel.

2. Build the component

typescript
import type { plugin } from 'wujie'
type lifecycle = (appWindow: Window) => any;
interface Props {
    /** The caller must guarantee uniqueness. */
    name: string;
    /** URL to render. */
    url: string;
    /** HTML to render; skip the URL request when supplied. */
    html?: string;
    /** Loading element. */
    loading?: HTMLElement;
    /** Route synchronization; when false, refresh sync is disabled but back/forward still works. */
    sync?: boolean;
    /** Child short-path replacement used during route synchronization. */
    prefix?: { [key: string]: string };
    /** Child keep-alive mode; state is preserved. */
    alive?: boolean;
    /** Data injected into the child application. */
    props?: { [key: string]: any };
    /** Execute JavaScript in fiber mode. */
    fiber?: boolean;
    /** Use the iframe fallback for the child application. */
    degrade?: boolean;
    /** Custom attributes for the runtime iframe. */
    attrs?: { [key: string]: any };
    /** Custom attributes for the fallback iframe. */
    degradeAttrs?: { [key: string]: any };
    /** Code replacement hook. */
    replace?: (codeText: string) => string;
    /** Custom fetch for resources and APIs. */
    fetch?: (input: RequestInfo, init?: RequestInit) => Promise<Response>;
    /** Child-application plugins. */
    plugins: Array<plugin>;
    /** Child-application lifecycle. */
    beforeLoad?: lifecycle;
    /** Not called when the child does not implement lifecycle integration. */
    beforeMount?: lifecycle;
    afterMount?: lifecycle;
    beforeUnmount?: lifecycle;
    afterUnmount?: lifecycle;
    /** Not called for applications without keep-alive. */
    activated?: lifecycle;
    deactivated?: lifecycle;
};

export { Props } 
typescript
import { startApp, bus } from 'wujie'
import { h, defineComponent, onMounted, getCurrentInstance, onBeforeUnmount } from 'vue'
import type { App, PropType } from 'vue'
import { Props } from './type'
const WuJie = defineComponent({
    props: {
        width: { type: String, default: "" },
        height: { type: String, default: "" },
        name: { type: String, default: "", required: true },
        loading: { type: HTMLElement, default: undefined },
        url: { type: String, default: "", required: true },
        sync: { type: Boolean, default: undefined },
        prefix: { type: Object, default: undefined },
        alive: { type: Boolean, default: undefined },
        props: { type: Object, default: undefined },
        attrs: { type: Object, default: undefined },
        replace: { type: Function as PropType<Props['replace']>, default: undefined },
        fetch: { type: Function as PropType<Props['fetch']>, default: undefined },
        fiber: { type: Boolean, default: undefined },
        degrade: { type: Boolean, default: undefined },
        plugins: { type: Array as PropType<Props['plugins']>, default: null },
        beforeLoad: { type: Function as PropType<Props['beforeLoad']>, default: null },
        beforeMount: { type: Function as PropType<Props['beforeMount']>, default: null },
        afterMount: { type: Function as PropType<Props['afterMount']>, default: null },
        beforeUnmount: { type: Function as PropType<Props['beforeUnmount']>, default: null },
        afterUnmount: { type: Function as PropType<Props['afterUnmount']>, default: null },
        activated: { type: Function as PropType<Props['activated']>, default: null },
        deactivated: { type: Function as PropType<Props['deactivated']>, default: null },
    },
    setup(props: Props, { emit }) {
        const instance = getCurrentInstance()
        const handlerEmit = (event: string, ...args: any[]) => {
            emit(event, ...args)
        }
        onMounted(() => {
            bus.$onAll(handlerEmit) // Subscribe to events
            // Initialize Wujie
            startApp({
                name: props.name,
                url: props.url,
                el: instance?.refs.wujie as HTMLElement,
                loading: props.loading,
                alive: props.alive,
                fetch: props.fetch,
                props: props.props,
                attrs: props.attrs,
                replace: props.replace,
                sync: props.sync,
                prefix: props.prefix,
                fiber: props.fiber,
                degrade: props.degrade,
                plugins: props.plugins,
                beforeLoad: props.beforeLoad,
                beforeMount: props.beforeMount,
                afterMount: props.afterMount,
                beforeUnmount: props.beforeUnmount,
                afterUnmount: props.afterUnmount,
                activated: props.activated,
                deactivated: props.deactivated,
            })
        })

        onBeforeUnmount(() => {
            bus.$offAll(handlerEmit) // Unsubscribe from events
        })

        return () => h('div', {
            style: {
                width: 200,
                height: 200
            },
            ref: "wujie"
        }, '')
    }
})


WuJie.install = (app: App) => {
    app.component('wujie', WuJie)
}

export default WuJie

Write the declaration file

typescript
import { bus, preloadApp, destroyApp, setupApp } from "wujie";
import type { App } from 'vue';

declare const WujieVue: {
    bus: typeof bus;
    setupApp: typeof setupApp;
    preloadApp: typeof preloadApp;
    destroyApp: typeof destroyApp;
    install: (app: App) => void
};

export default WujieVue;

Write package.json

json
{
  "name": "wujie-vue-setup",
  "version": "0.0.4",
  "description": "",
  "main": "lib/index.js",
  "module": "esm/index.js",
  "files": [
     "esm",
     "lib",
     "index.d.ts"
  ],
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "wujie": "^1.0.13"
  },
  "devDependencies": {
    "@swc/core": "^1.3.42",
    "swc-loader": "^0.2.3",
    "ts-loader": "^9.4.2",
    "typescript": "^5.0.2",
    "vue": "^3.2.47",
    "webpack": "^5.77.0",
    "webpack-cli": "^5.0.1"
  }
}

After implementation, run npm adduser to create an account, npm login to sign in, and npm publish to publish. Before publishing, remember to check that the configured registry is npm.

Wujie preloading and its principles

Export preloadApp from the Wujie instance. Its parameters match startApp, and preloading must enable the exec option.

For example

javascript
preloadApp({ name: "vue3", url: "http://127.0.0.1:5174/", exec: true })
preloadApp({ name: "react", url: "http://127.0.0.1:5175/", exec: true })

The default value of fiber is true.

This controls JavaScript execution. Because a child application can block the host's rendering thread, setting it to true executes JavaScript intermittently in a React Fiber-like manner. Each JavaScript file is wrapped in requestIdleCallback, allowing external input to receive a response between files. The granularity is one file, so if a child has a very large file, split the bundle to maximize the benefit of fiber mode.

How it works

The requestIdleCallback API runs when the browser is idle. What exactly does browser idle time mean?

Original figure 9

Most mainstream PC displays refresh at 60 Hz, or sixty times per second, giving each refresh an average budget of about 16.6 ms.

Idle time exists only after input, rendering, and composition for a frame have completed. Work must finish within 16.6 ms before the remaining time can be given to requestIdleCallback.

A second case occurs when there are no tasks to run: the browser may have a 50 ms idle period in which it can also run requestIdleCallback.

What happens within one frame?

  1. Handle user events such as click, input, and change.

  2. Execute timer tasks.

  3. Execute requestAnimationFrame.

  4. Perform DOM reflow and repaint.

  5. Calculate drawing instructions for updated layers.

  6. Merge drawing instructions on the main thread; if time remains, execute requestIdleCallback.

How does this relate to React Fiber?

React has a similar mechanism, but it does not use requestIdleCallback, because testing showed that it may exceed 16 ms and make rendering appear janky. React 16 used requestAnimationFrame + postMessage. Why not setTimeout? Even with a delay of zero, setTimeout has a minimum delay of about 4 ms, so postMessage was used. React 18 switched to MessageChannel to execute work through a queue.

Passing data with Wujie

1. As discussed earlier, Wujie stores child-app JavaScript in an iframe, so applications can communicate through window.

Define a global variable in the host application.

javascript
var a = 'xiaoman'

The child application can access it through window.parent.a.

javascript
const send = () => {
  console.log(alert(window.parent.a))
}

2. Inject parameters into the child through props

vue
<WujieVue :props="{name:'xm',age:18}"  url="http://127.0.0.1:5174/" name="vue3"></WujieVue> <!-- Vue 3 child application -->

The child application can obtain them through $wujie:

javascript
window.$wujie.props

If $wujie reports a type error, add a declaration file.

typescript
declare global {
    interface Window {
        $wujie:{
            props:Record<string,any>
        }
    }
}

3. Event bus

The host listens through the bus.

javascript
import {bus} from 'wujie'
bus.$on('vue3', (data: any) => {
    console.log(data)
})

The child triggers an event with emit. The reverse also works: the host can emit and the child can listen with on.

javascript
 window.$wujie.bus.$emit('vue3', {name:'xm',age:18})

Module Federation

Why discuss this? Many people do not consider it micro frontend, while others do; it depends on the interpretation. I regard it as a decentralized technology that lets independently built applications dynamically call one another's modules. This runtime mechanism makes applications easy to split and enables true cross-application module sharing.

It is tightly coupled to Webpack 5 and uses a built-in Webpack 5 plugin, so no installation is required.

javascript
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin')

Demonstration:

Create two projects: one host and one remote.

Original figure 10

The scenario is that the host project wants to use the remote project's list module.

Webpack configuration for the remote project

javascript
const { Configuration  } = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin')
/**
 * @type {Configuration} // Enable configuration IntelliSense
 */
const config = {
    mode: "none",
    entry: "./index.js",
    output: {
        filename: "bundle.js"
    },
    devServer:{
        port:9002 //remote 9002
    },
    plugins:[
        new HtmlWebpackPlugin({
            template: "./index.html"
        }),
        new ModuleFederationPlugin({
            name: "remote", // name is required
            filename: "remoteEntry.js", // filename is required; generated output name
            exposes: {
                "./addList": "./list.js" // Exposed module
            },
        })
    ]
}

module.exports = config

Webpack configuration for the host project

javascript
const { Configuration  } = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin')
/**
 * @type {Configuration} // Enable configuration IntelliSense
 */
const config = {
    mode: "none",
    entry: "./index.js",
    output: {
        filename: "bundle.js"
    },
    devServer:{
        port:9001
    },
    plugins:[
        new HtmlWebpackPlugin({
            template: "./index.html"
        }),
        new ModuleFederationPlugin({
            name: "host", // name is required
            filename: "hostEntry.js", // filename is required; generated output name
            // remote matches the remote project's ModuleFederationPlugin name; the URL uses its port and filename
            remotes: {
                remote: "remote@http://localhost:9002/remoteEntry.js" // Import the module
            },
        })
    ]
}

module.exports = config

The host uses the module, which is loaded asynchronously.

javascript
// remote matches the remote project name; addList matches the exposed key 
import('remote/addList').then(({ addList }) => {
   let app = document.querySelector('#app');

   app.innerHTML = `
   <h3>Host</h3>
`;
   addList()
})

Build the projects and inspect the result.

This is essentially a CDN import. Why do it this way?

Previously, if ten projects shared a module published to npm at version 1.0.0 and it changed to 1.0.1, every project had to reinstall it, which was cumbersome. Module Federation loads it through a CDN, so no reinstall is needed and every load uses the latest version.

Original figure 11