The umi app opens the micro-frontend with one click:
The configuration of the main application:
Step 1: Add the plugin
yarn add @umijs/plugin-qiankun -D
Step 2: Open qiankun
import { defineConfig } from 'umi';
export default defineConfig({
qiankun: {
master: {
// 注册子应用信息
apps: [
{
name: 'app', // 唯一 id
entry: '//localhost:8001/', // html entry
},
],
},
},
});
Step 3: Configure sub-applications
routing:
import { defineConfig } from 'umi';
export default defineConfig({
routes: [
{
path: '/',
component: '../layouts/index.js',
routes: [
// 配置 app 关联的路由
{
path: '/app',
microApp: 'app',
},
{
path: '/',
component: './index.js',
},
],
},
],
});
Components:
import { MicroApp } from 'umi';
export function MyPage() {
return (
<div>
<MicroApp name="app" />
</div>
)
}
Configuration of sub-apps:
Step 1: Add the plugin
yarn add @umijs/plugin-qiankun -D
Step 2: Plugin registration
import { defineConfig } from 'umi';
export default defineConfig({
qiankun: {
slave: {}
}
});
Step 3: Configure runtime lifecycle hooks (optional)
in app.js[ts]
export const qiankun = {
// 应用加载之前
async bootstrap(props) {
console.log('app1 bootstrap', props);
},
// 应用 render 之前触发
async mount(props) {
console.log('app1 mount', props);
},
// 应用卸载之后触发
async unmount(props) {
console.log('app1 unmount', props);
},
};
Communication between parent and child apps - main app:
Use routing:
in app.js[ts]
export function useQiankunStateForSlave() {
const [masterState, setMasterState] = useState({});
return {
masterState,
setMasterState,
};
}
Use useModel:
import { useState } from 'react';
import { MicroApp } from 'umi';
export function MyPage() {
const [name, setName] = useState();
return (
<div>
<MicroApp name="app" name={name} onNameChange={(newName) => setName(newName)} />
</div>
)
}
Communication between parent and child apps - child apps:
Use the higher-order component connectMaster:
import { connectMaster } from 'umi';
function MyPage(props) {
return <div>{JSON.stringify(props)}</div>;
}
export default connectMaster(MyPage);
Use useModel:
import { useModel } from 'umi';
function MyPage() {
const masterProps = useModel('@@qiankunStateFromMaster');
return <div>{JSON.stringify(masterProps)}</div>;
}