这确定错过最新版的qiankun接入方法?

286 阅读2分钟

前言

目前的官方并没有提供任何关于vue3+vite相关使用的方法,但是最近突然想做使用微前端开发的中后台管理系统,经过长时间的思想斗争,最终决定使用vue+vite,主应用和子应用都使用。但奈何翻遍文档,都没有找到官方的方法。

但奈何我等不住,官方没有,那就自己造。

应该怎么造呢? 自己解决不了总有人解决了,万能网友登场了,应该多方查找,终于搞定。下面是我的改造过程。

只是基础的引入,不喜勿喷,如果你另有高见,以你的为准。主要是为迷茫的你有点思路,也方便自己日后方便回忆。

主应用

  1. 创建应用
    pnpm create vite
  1. 安装插件
    pnpm add qiankun -S
  1. 配置
cd src
mkdir micro
touch index.ts

src/micro/index.ts文件中输入如下内容,用做子应用的配置和启动


import { registerMicroApps, start } from 'qiankun';


registerMicroApps([
  {
    name: 'reactApp', // 子应用名称
    entry: '//localhost:3000', // 入口地址
    container: '#container', // 挂在的容器
    activeRule: '/app-react', // 激活的路由
  },
  {
    name: 'vueApp',
    entry: '//localhost:8080',
    container: '#container',
    activeRule: '/app-vue',
  }
]);
// 启动 qiankun
start();

然后在src/mian.ts中引入

 import './micro/index.ts`

src/App.vue添加

<template>
    <router-view />
    <div id='container'></div>
</template>

子应用

  1. 创建应用
    pnpm create vite
  1. 安装插件
    pnpm add vite-plugin-qiankun -S
  1. vite.config.ts中配置如下
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import qiankun from "vite-plugin-qiankun";

export default defineConfig({
  server: {
    host: "0.0.0.0",
    port: 30000
  },
  plugins: [vue(), qiankun("apps", { useDevMode: true })]
});
  1. 配置路由src/router/index.ts
import { createRouter, createWebHistory } from "vue-router";
import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";

const routes = [];

const router = createRouter({
  history: createWebHistory(
    qiankunWindow.__POWERED_BY_QIANKUN__ ? "/apps/" : "/"
  ),
  routes
});

export default router;

配置路由这儿有个注意点

这个base Router要和主应用中的 activeRule的值保持一致。

  1. 入口文件配置src/mian.ts
import { createApp } from "vue";
import router from "./router";
import App from "./App.vue";
import {
  renderWithQiankun,
  qiankunWindow
} from "vite-plugin-qiankun/dist/helper";

import "ant-design-vue/dist/reset.css";

function render(container?: HTMLElement) {
  const app = createApp(App);

  app.use(router);

  app.mount(container ? container : "#apps");
}

const initQianKun = () => {
  renderWithQiankun({
    mount(props) {
      render(props.container);
    },
    bootstrap() {},
    unmount() {},
    update() {}
  });
};

qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun() : render();

总结

其实主要是子应用的需要vite-plugin-qiankun模块去处理。