Mastering Micro‑Frontends with Qiankun: From Basics to APAAS Integration
This article explores the concept of micro‑frontends, introduces the Qiankun framework, demonstrates its rendering workflow with practical code examples, and details an APAAS‑based architecture for integrating and managing micro‑applications, covering client‑side SDK, server proxies, routing, sandboxing, CSS isolation, and third‑party SDK challenges.
Introduction
Micro‑Frontends are an architecture similar to micro‑services applied to the browser, turning a monolithic web app into a collection of small front‑end applications.
Micro‑frontends are not new; early goals were to support different technology stacks and reuse pages/components across systems. The single‑spa project inspired the idea by treating the whole page as a component.
Ant Financial later created the qiankun framework based on single‑spa to address the challenges of large “frontend monoliths” that become hard to maintain as teams and features grow.
The author found qiankun limited for rapid build, publish, and management, and therefore explored an APAAS approach to integrate qiankun applications quickly into other business systems.
Qiankun Overview
The following outlines the rendering process of qiankun to help readers unfamiliar with micro‑frontends.
Who is it about?
What happened?
When did it take place?
Where did it take place?
Why did it happen?
A sample scenario: System A wants to embed a “welcome card configuration” page from System B.
The three participants are the qiankun client, the main app (A), and the micro‑app (B). The first step is to register routes, which determines when and where the micro‑frontend starts rendering.
<code>import { registerMicroApps, start } from 'qiankun';
registerMicroApps([
{
name: 'smart-contact-cms-index', // app name registered
entry: '//localhost:7100',
container: '#yourContainer',
activeRule: '/yourActiveRule',
},
]);
start();</code>This simple example uses
nameas the unique identifier,
entryas the resource URL, and renders the micro‑app into the DOM node identified by
#yourContainerwhen the route matches
/yourActiveRule.
<code>const packageName = require('./package.json').name;
module.exports = {
output: {
library: `${packageName}-[name]`,
libraryTarget: 'umd',
jsonpFunction: `webpackJsonp_${packageName}`,
},
};</code>The above webpack configuration sets the library name that matches the
nameused in route registration.
Qiankun intercepts the HTML of the micro‑app, constructs HTTP requests to load JS files, and needs a marker (the
library) to identify the entry script.
Excerpt of
index.jsentry code:
<code>!function(e,t){...}</code>Because a normal React app would call
ReactDOM.renderdirectly, qiankun requires the micro‑app to expose lifecycle hooks so that the client can control rendering.
<code>// Single app run
if (!isMicroApp) {
// Non‑micro‑frontend rendering
renderApp({});
}
// Export qiankun lifecycle
export const bootstrap = async () => {
console.log('[smart-contact-cms] bootstrap');
};
export const mount = async (props) => {
console.log('[smart-contact-cms] mount', props);
normalizeObject(props.mainAppState);
// Run as micro‑app
renderApp(props);
};
export const unmount = async (props) => {
const { container } = props;
ReactDOM.unmountComponentAtNode(
container ? container.querySelector('#root') : document.querySelector('#root')
);
};</code>The variable
__POWERED_BY_QIANKUN__on
windowindicates whether the code runs inside qiankun. Resource requests are performed via Fetch/XHR, allowing custom authentication.
These mechanisms enable sandboxing of micro‑apps.
APAAS Architecture Overview
Due to space, only the client side, server‑side proxy, and micro‑app transformation are described.
Client Side
The client is a qiankun SDK wrapped with business logic, exposing the following interfaces:
1. initial(appInfo)
<code>{
"app_id": "xxx",
"prefetch": true,
"signUrl": "remote-url"
}</code>This initializes authentication, pre‑loading, and app identification.
2. load(FLoadConfig)
Dynamic loading of a micro‑app uses the following TypeScript interface:
<code>interface FLoadConfig {
container: string;
pageId: string;
props?: FMicroProps;
}
interface FMicroProps {
loginUrl?: string; // redirect on auth failure
baseApiUrl?: string;
dispatch?: (value: { type: string; data: any }) => void;
pageInfo?: FPageConfig;
useNativeRoute?: number;
extra?: any;
}</code> loginUrlis the redirect for authentication failures,
baseApiUrlis the backend address, and
useNativeRoutecontrols routing mode.
The implementation solves cross‑origin authentication and path conflicts between host and micro‑apps.
Routing modes:
0 – use the route returned by the configuration service.
1 – prepend the current page hash to the configured route.
3 – keep the current page route unchanged (default 0).
In
renderApp, the host route prefix is passed to the micro‑app.
<code>export const mount = async (props) => {
console.log('[smart-contact-cms] mount', props);
normalizeObject(props.mainAppState);
// Run as micro‑app
renderApp(props);
};</code>The client also provides
subscribe(callback)to listen for events such as
load.
Server‑Side Proxy
The goal is low‑cost integration of micro‑apps without requiring the host to understand each backend. By delegating authentication to Tencent Cloud APIs, the host only needs to interact with a unified proxy.
Micro‑App Transformation
Transforming an existing project into a micro‑app mainly involves sandboxing and isolation.
CSS isolation is achieved with CSS Modules or PostCSS plugins that add a unique prefix (e.g.,
@ant-prefix: 'industryAnt') to Ant Design classes.
<code>css: {
loaderOptions: {
less: {
javascriptEnabled: true,
modifyVars: {
'@ant-prefix': 'industryAnt',
'primary-color': '#0052d9',
// other variables …
},
module: true,
},
postcss: {
plugins: [AddAntClass({ prefix: 'industryAnt' })],
},
},
}</code>For third‑party SDKs like WeChat, qiankun cannot fetch the scripts due to security policies, so the scripts must be loaded directly in the HTML header or blocked via a custom fetch implementation.
FAQ sections address SDK loading failures, CSS isolation strategies, and handling of dynamic component styles in Ant Design.
FAQ
1. How to solve third‑party SDK script loading failures?
WeChat SDKs must be included in the page header; qiankun’s script interception can break them. Solutions include filtering scripts with
getTemplate, custom fetch to block scripts, or changing the HTML content‑type. Prefetching must be disabled when using these solutions.
2. CSS isolation
Micro‑frontends aim for technology‑stack independence. Strict sandboxing isolates global variables but CSS isolation remains challenging. Using CSS Modules or PostCSS prefixing can mitigate conflicts, though dynamic component styles may still require manual adjustments.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.