vue3微前端架构——基于蚂蚁qiankun框架
楔子
首先,目前qiankun框架尚不支持vite,
微应用不能使用vite创建,
即使只是生产环境加的载微应用也不行,
因为vite打包代码时,内部的esbuild会tree shake掉与qiankun相关的生命周期钩子,
主应用没影响,使用什么创建项目都无所谓
主应用
没啥特殊的,随便一个组件里留个容器div
<div id="container"></div>
在一个方法内加载微应用
import { loadMicroApp } from 'qiankun'; export default { setup(){ let create = ()=>{ loadMicroApp({ name: 'vue3', entry: 'http://localhost:7105/', container: '#container', }); } return {create}; } }
通过路由注册微应用的方式,请自己看文档
微应用
配置文件:vue.config.js
const path = require('path'); const { name } = require('./package'); function resolve(dir) { return path.join(__dirname, dir); } const port = 7105; module.exports = { outputDir: 'dist', assetsDir: 'static', filenameHashing: true, devServer: { hot: true, disableHostCheck: true, port, overlay: { warnings: false, errors: true, }, headers: { 'Access-Control-Allow-Origin': '*', }, }, // 自定义webpack配置 configureWebpack: { resolve: { alias: { '@': resolve('src'), }, }, output: { // 把子应用打包成 umd 库格式 library: `${name}-[name]`, libraryTarget: 'umd', jsonpFunction: `webpackJsonp_${name}`, }, }, };
router.js
import HelloWorld from "./components/HelloWorld.vue"; import HelloWorld2 from "./components/HelloWorld2.vue"; import { createRouter, createWebHistory } from "vue-router"; const routes = [ { path: "/", component: HelloWorld }, { path: "/about", component: HelloWorld2 }, ]; const router = createRouter({ history: createWebHistory(window.__POWERED_BY_QIANKUN__ ? "/vue3" : "/"), routes, }); export default router;
main.js
这里有好多钩子,是给主应用用的
if (window.__POWERED_BY_QIANKUN__) { // eslint-disable-next-line no-undef __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__; } import { createApp } from "vue"; import App from "./App.vue"; import router from "./router"; let instance = null; function render(props = {}) { const { container } = props; instance = createApp(App); instance.use(router); instance.mount(container ? container.querySelector("#app") : "#app"); } if (!window.__POWERED_BY_QIANKUN__) { render(); } export async function bootstrap() { console.log("%c ", "color: green;", "vue3.0 app bootstraped"); } export async function mount(props) { render(props); instance.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange; instance.config.globalProperties.$setGlobalState = props.setGlobalState; } export async function unmount() { instance.unmount(); instance._container.innerHTML = ""; instance = null; }
app.vue
<template> <button @click="go('/')">home</button> <button @click="go('/about')">sub</button> <router-view></router-view> </template> <script> import router from "./router" export default { setup(){ let go = (p)=>{ router.push(p) } return {go} } } </script>