一个简单的前端微服务部署--qiankun

时间:2024-03-23 12:38:34

qiankun:基于single-spa封装,开箱即用。

一、主应用接入

1、安装qiankun

npm i qiankun -S

2、主应用注册子应用

//children-app.ts
import { registerMicroApps } from 'qiankun';
import shared from "./shared";
registerMicroApps([
  {
    name: 'subapp',
    entry: 'http://localhost:3001',
    container: '#subapp',
    activeRule: '#/subapp'
  }
]);

//入口文件 main.ts
import './children-app';

3、在主应用的路由页面加载子应用

import { start } from 'qiankun';
onMounted(() => {
  if (!window.qiankunStarted) {
    window.qiankunStarted = true;
    start();
  }
})

二、子应用接入

1、安装

npm i qiankun vite-plugin-qiankun -S

2、修改打包配置项

//vite.config.ts
import qiankun from 'vite-plugin-qiankun';
export default defineConfig({
  base: 'http://localhost:3001/', //base设为绝对路径
  plugins: [
    vue(),
    qiankun('flow-graph', {
      useDevMode: true
    })
  ]
});

3、修改入口文件


//main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import {
  renderWithQiankun,
  qiankunWindow
} from 'vite-plugin-qiankun/dist/helper';
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  createApp(App).use(router).mount('#app');
} else {
  let app: VueApp<Element>;
  renderWithQiankun({
    mount(props) {
      console.log('--mount');
      app = createApp(App);
      app
        .use(router)
        .mount(
          (props.container
           ? props.container.querySelector('#app')
           : document.getElementById('app')) as Element
        );
    },
    bootstrap() {
      console.log('--bootstrap');
    },
    update() {
      console.log('--update');
    },
    unmount() {
      console.log('--unmount');
      app?.unmount();
    }
  });
}