Bootstrap

umi一键开启微前端

GitHub - umijs/umi-plugin-qiankun: Umi plugin for qiankun.Umi plugin for qiankun. Contribute to umijs/umi-plugin-qiankun development by creating an account on GitHub.https://github.com/umijs/umi-plugin-qiankun

umi 应用一键开启微前端:

主应用的配置: 

第一步:添加插件

yarn add @umijs/plugin-qiankun -D

 第二步:开启qiankun

import { defineConfig } from 'umi';
export default defineConfig({
  qiankun: {
    master: {
      // 注册子应用信息
      apps: [
        {
          name: 'app', // 唯一 id
          entry: '//localhost:8001/', // html entry
        },
      ],
    },
  },
});

第三步:配置子应用

路由:

import { defineConfig } from 'umi';
export default defineConfig({
  routes: [
    {
      path: '/',
      component: '../layouts/index.js',
      routes: [
        // 配置 app 关联的路由
        {
          path: '/app',
          microApp: 'app',
        },
        {
          path: '/',
          component: './index.js',
        },
      ],
    },
  ],
});

组件:

import { MicroApp } from 'umi';

export function MyPage() {

  return (
    <div>
        <MicroApp name="app" />
    </div>
  )
}

子应用的配置: 

 第一步:添加插件

yarn add @umijs/plugin-qiankun -D

 第二步:插件注册

import { defineConfig } from 'umi';

export default defineConfig({
  qiankun: {
    slave: {}
  }
});

第三步:配置运行时生命周期钩子(可选)

在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);
  },
};

父子应用之间的通信-主应用:

使用路由: 

在app.js[ts]中

export function useQiankunStateForSlave() {
  const [masterState, setMasterState] = useState({});

  return {
    masterState,
    setMasterState,
  };
}

使用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>
  )
}

 父子应用之间的通信-子应用:

使用高阶组件connectMaster: 

import { connectMaster } from 'umi';

function MyPage(props) {
  return <div>{JSON.stringify(props)}</div>;
}

export default connectMaster(MyPage);

使用useModel :

import { useModel } from 'umi';

function MyPage() {
  const masterProps = useModel('@@qiankunStateFromMaster');
  return <div>{JSON.stringify(masterProps)}</div>;
}

;