1291 words
6 minutes
Embedding a Legacy Project Built on a Different Tech Stack with the Qiankun Micro-Frontend Framework

Final Result#

My team recently took on a requirement that amounted to a mini low-code platform: the front end would be a drag-and-drop builder for data dashboards. Building that from scratch would have burned an enormous number of engineering hours, so we went looking on GitHub for an open-source project that could get us most of the way there.

We settled on AJ-Report. The catch: phase one of this requirement would be developed inside another system (React), and phase two would likely spin the platform into a product of our own — but AJ-Report is a Vue 2 project, which fits neither phase. After more digging we found nothing better in the open-source world, so I decided to embed it into a host application using a micro-frontend architecture.

Phase One#

For phase one, all we needed was to adapt it into a micro-app and embed it into the existing system. The concrete configuration changes are covered under phase two below.

Phase Two#

Phase two calls for at least three projects: the host application, the open-source drag-and-drop dashboard micro-app, and a business-logic micro-app.

Since the whole team works in React, the host app and the business micro-app are React as well.

The Host App#

  1. Scaffold it with Create React App:
Terminal window
npx create-react-app cra-framework --template typescript
  1. Install Qiankun
Terminal window
npm i qiankun -S
  1. Install the router and configure routes
Terminal window
npm install react-router-dom

The routes and layout look like this:

Routes and layout

  1. Register and start the micro-app
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import RouterGurad from './router/RouterGurad';
import reportWebVitals from './reportWebVitals';
import { registerMicroApps, start, initGlobalState, MicroAppStateActions } from 'qiankun';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<BrowserRouter>
<RouterGurad />
</BrowserRouter>
</React.StrictMode>
);
// If you want to start measuring performance in your app, visit: https://bit.ly/CRA-vitals
reportWebVitals();
registerMicroApps([
{
name: 'app-vue',
entry: '//localhost:9528',
container: '#root',
activeRule: '/app-vue',
},
{
name: 'cra-sub-web',
entry: '//localhost:3002',
container: '#main',
activeRule: '/cra-sub-web',
},
]);
// start qiankun
start();

The Drag-and-Drop Dashboard Micro-App#

  1. Add public-path.js under src:
if (window.__POWERED_BY_QIANKUN__) {
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
  1. Rework the entry file main.js. To keep the root id #app from clashing with DOM from other apps, the element lookup has to be scoped.

The relevant changes cluster at the bottom — the exported bootstrap, mount, and unmount lifecycle hooks plus the Vue mounting (there is plenty of pre-existing code here that has nothing to do with the micro-frontend conversion):

import Vue from 'vue'
import './public-path';
import VueRouter from 'vue-router';
// element-ui
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import 'normalize.css/normalize.css'// A modern alternative to CSS resets
import '@/assets/styles/common.css'
import '@/assets/styles/index.scss'// custome global css
// app router vuex filter mixins
import App from './App'
import router from './router'
import store from './store'
import * as filter from './filter'
import mixins from '@/mixins'
import echarts from 'echarts';
// Register echarts globally
Vue.component('v-chart', ECharts)
import ECharts from 'vue-echarts'
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/tooltip'
//import 'echarts-liquidfill'
// import 'echarts-gl'
import dataV from '@jiaminghi/data-view'
Vue.use(dataV)
// anji component
import anjiCrud from '@/components/AnjiPlus/anji-crud/anji-crud'
import anjiSelect from '@/components/AnjiPlus/anji-select'
import anjiUpload from '@/components/AnjiPlus/anji-upload'
Vue.component('anji-upload', anjiUpload)
Vue.component('anji-crud', anjiCrud)
Vue.component('anji-select', anjiSelect)
// permission control
import '@/permission'
// Directive for button-level permissions
import permission from '@/components/Permission/index'
Vue.use(permission);
import Avue from '@smallwei/avue';
import '@smallwei/avue/lib/index.css';
Vue.use(Avue);
// enable element zh-cn
Vue.use(ElementUI, { zhLocale })
// register global filter.
Object.keys(filter).forEach(key => {
Vue.filter(key, filter[key])
})
// register global mixins.
Vue.mixin(mixins)
// Default page sizes for pagination
Vue.prototype.$pageSizeAll = [10, 50, 100, 200, 500]
// create the app instance.
// new Vue({ el: '#app', router, store, render: h => h(App) })
Vue.config.productionTip = false;
let instance = null;
function render(props = {}) {
const { container } = props;
router.base = window.__POWERED_BY_QIANKUN__ ? '/app-vue/' : '/';
instance = new Vue({
el: container ? container.querySelector('#app') : '#app',
router,
store,
render: (h) => h(App),
});
}
// standalone runtime
if (!window.__POWERED_BY_QIANKUN__) {
render();
}
export async function bootstrap() {
console.log('[vue] vue app bootstraped');
}
export async function mount(props) {
console.log('[vue] props from main framework', props);
render(props);
}
export async function unmount() {
console.log('[vue] vue app unmount');
instance.$destroy();
instance.$el.innerHTML = '';
instance = null;
// router = null;
}
  1. Adjust the build config (vue.config.js):

This project’s scaffold version doesn’t ship a vue.config.js, so the webpack config is edited directly:

const devWebpackConfig = merge(baseWebpackConfig, {
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: config.dev.assetsPublicPath,
library: 'app1',
libraryTarget: 'umd', // package the micro-app as a UMD library
jsonpFunction: `webpackJsonp_${name}`, // webpack 5: replace jsonpFunction with chunkLoadingGlobal
},
devServer: {
headers: {
'Access-Control-Allow-Origin': '*',
},
}
});

With that in place, visiting http://localhost:3001/app-vue#/bigscreen/designer?reportCode=test_001 gives you:

Untitled

The Business Micro-App#

  1. Scaffold it with Create React App:
npx create-react-app cra-sub-web --template typescript
  1. Add public-path.js under src:
if (window.__POWERED_BY_QIANKUN__) {
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
  1. Set the base for the history-mode router:
<BrowserRouter basename={window.__POWERED_BY_QIANKUN__ ? '/app-react' : '/'}>
  1. Rework the entry file index.js the same way — scope the #root lookup so the id can’t clash with DOM from other apps.
import React from 'react';
import './public-path';
import ReactDOM from 'react-dom/client';
import routes from './router';
import { BrowserRouter, useRoutes } from 'react-router-dom';
import './index.css';
let root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
function App () {
return useRoutes(routes)
}
// @ts-ignore
console.log(window.__POWERED_BY_QIANKUN__);
// @ts-ignore
if (!window.__POWERED_BY_QIANKUN__) {
root.render(
<React.StrictMode>
{/* @ts-ignore */}
<BrowserRouter basename={window.__POWERED_BY_QIANKUN__ ? '/cra-sub-web' : '/'}>
<App />
</BrowserRouter>
</React.StrictMode>
);
}
export async function bootstrap() {
console.log('[react16] react app bootstraped');
}
export async function mount(props: any) {
console.log('[react16] props from main framework', props);
const { container } = props;
root = ReactDOM.createRoot(container ? container.querySelector('#root') as HTMLElement : document.getElementById('root') as HTMLElement);
console.log(container ? container.querySelector('#root') as HTMLElement : document.getElementById('root') as HTMLElement);
root.render(
<React.StrictMode>
{/* @ts-ignore */}
<BrowserRouter basename={window.__POWERED_BY_QIANKUN__ ? '/cra-sub-web' : '/'}>
<App />
</BrowserRouter>
</React.StrictMode>
);
}
export async function unmount(props: any) {
// unmount
root.unmount();
}
  1. Modify the webpack config

I used react-app-rewired for this. Install it:

npm install react-app-rewired --save-dev

Update package.json

{
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
}
}

Create config-overrides.js

const { override, addWebpackAlias } = require('customize-cra');
const path = require('path');
const { name } = require('./package');
module.exports = {
webpack: override(
(config) => {
config.output.library = `${name}-[name]`;
config.output.libraryTarget = 'umd';
// webpack 5: replace jsonpFunction with chunkLoadingGlobal
config.output.chunkLoadingGlobal = `webpackJsonp_${name}`;
config.output.globalObject = 'window';
return config;
},
addWebpackAlias({
'@': path.resolve(__dirname, 'src'),
})
),
devServer: (configFunction) => {
const config = configFunction;
config.headers = {
'Access-Control-Allow-Origin': '*',
};
config.historyApiFallback = true;
config.hot = false;
config.watchContentBase = false;
config.liveReload = false;
return config;
},
};

Restart the dev server and open http://localhost:3001/cra-sub-web/home:

Untitled

Communication Between Apps#

Following the docs, we used GlobalState, which behaves much like an event bus.

First, define the state in the host app:

import { initGlobalState, MicroAppStateActions } from 'qiankun';
const state = {
status: 1,
};
const actions: MicroAppStateActions = initGlobalState(state);
actions.onGlobalStateChange((state, prev) => {
// state: the state after the change; prev: the state before it
console.log(state, prev);
if (state.status === 0) {
alert('token expired, redirecting to login');
window.location.href = '/home';
}
});

The micro-app consumes it from its mount hook — here the functions are stashed on the Vue instance:

export async function mount(props) {
console.log('[vue] props from main framework', props);
Vue.prototype.$onGlobalStateChange = props.onGlobalStateChange;
Vue.prototype.$setGlobalState = props.setGlobalState;
render(props);
}
// usage
Vue.prototype.$setGlobalState({
status: 2
});

In practice, though, the console threw a warning that this API is scheduled for removal in qiankun 3.0 and is no longer recommended:

Untitled

In a GitHub issue the maintainers suggest attaching shared state to the window object instead. The final version:

const state = {
status: 1,
};
// attach the __qiankun__.$state global to window
window.__qiankun__ = {};
window.__qiankun__.$state = state;
// watch for changes to window.__qiankun__.$state
window.__qiankun__.$state = new Proxy(state, {
set: function (target, key, value) {
console.log('set', key, value);
if (key === 'status' && value === 0) {
alert('token expired, redirecting to login');
window.location.href = '/home';
}
return Reflect.set(target, key, value);
},
});

Inside the micro-app, console.log(window.qiankun.$state) now prints successfully:

Untitled

And setting window.qiankun.$state.status to 0 from the micro-app is picked up by the host app:

Untitled

Embedding a Legacy Project Built on a Different Tech Stack with the Qiankun Micro-Frontend Framework
https://www.mihouo.com/en/posts/front/embedding-legacy-projects-with-different-tech-stacks-using-qiankun-micro-frontend/
Author
Jia
Published at
2024-07-02
License
CC BY-NC-SA 4.0