qiankun 是一个基于 single-spa的微前端实现库,主应用微应用都能做到技术栈无关,qiankun 对于用户而言只是一个类似 jQuery 的库,你需要调用几个 qiankun 的 API 即可完成应用的微前端改造。
这里使用angular作为基座,vue作为子应用进行搭建,使用其他框架也是类似操作
demo效果
搭建Angular基座
1、创建一个angular应用
npm install -g @angular/cli ng new angularApp
2、主应用安装qiankun
cd angularApp npm install qiankun npm i qiankun-ng-common -S
3、主应用中配置
3.1 在src目录下创建registerApps.js用来配置子应用
import {registerMicroApps,start} from 'qiankun';
const loader = (loading) => {
console.log(loading)
}
registerMicroApps([{
name: 'm-vue',
entry: '//localhost:20000',
container: '#container',
activeRule: '/vue',
loader
},
],{
beforeLoad:()=> {
console.log('加载前')
},
beforeMount:()=> {
console.log('挂载前')
},
afterMount:()=> {
console.log('挂载后')
},
beforeUnmount:()=> {
console.log('销毁前')
},
afterUnmount:()=> {
console.log('销毁后')
}
})
start({
});
3.2 在main.ts中引入registerApps.js)
3.3 配置默认路由,避免路由到子项目报错
import { EmptyComponent } from 'qiankun-ng-common';
const routes: Routes = [
{
path: '**',
component: EmptyComponent
}
];
3.4 配置子项目放置和跳转
<!-- app.component.html -->
<div class="content" role="main">
<a [routerLink]="['vue']">vue子应用</a>
<a [routerLink]="['react']">react子应用</a>
<div id="container"></div>
</div>
搭建vue3子应用
1、创建一个vue3应用
npm install -g @vue/cli
vue create m-vue
2、子应用配置
2.1 导出相应的生命周期钩子
2.1.1 对router/index.js 文件进行改造
2.2.2 对main.js文件进行改造
import { createApp } from 'vue'
import { createRouter,createWebHistory } from 'vue-router';
import App from './App.vue'
import routes from './router'
let history;
let router;
let app;
function render(props = {}){
history = createWebHistory('/vue');
router = createRouter({
history,
routes
})
app = createApp(App);
let {container} = props
app.use(router).mount(container ? container.querySelector('#app'):'#app')
}
if(!window.__POWERED_BY_QIANKUN__){
render()
}
export async function bootstrap(){
console.log('vue3 app bootstraped')
}
export async function mount(props){
console.log('vue3 app mount');
render(props)
}
export async function unmount(){
console.log('vue3 app unmount')
history = null;
app = null;
router = null
}
2.2 配置微应用的打包工具
修改vue.config.js文件
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
publicPath: "//localhost:20000",
devServer: {
port: 20000,
headers: {
'Access-Control-Allow-Origin': '*',
},
},
configureWebpack: {
output:{
libraryTarget:'umd',
library:'m-vue'
}
}
})
项目启动
Angular : ng serve --open vue: npm run serve
single-spa文档 : https://zh-hans.single-spa.js.org/docs/getting-started-overview qiankun文档:https://qiankun.umijs.org/zh/guide
|