完整代码地址在microfrontend-learning
1. 主应用改造
修改activeRule
如:
[
{
name: "ReactMicroApp",
entry: process.env.VUE_APP_REACT_MICRO_APP,
container: "#frame",
activeRule: "/#/microApp/react",
},
{
name: "VueMicroApp",
entry: process.env.VUE_APP_VUE_MICRO_APP,
container: "#frame",
activeRule: "/#/microApp/vue",
}
]
路由部分修改
2. vue子应用修改
router修改
import Home from '@/pages/home/index.vue';
let prefix = window.__POWERED_BY_QIANKUN__ ? '/microApp/vue/' : '/';
const routes = [
{
path: prefix == '/' ? prefix : prefix.substring(0, prefix.length - 1),
name: 'Home',
component: Home
},
{
path: prefix + 'about',
name: 'About',
component: () => import('@/pages/about/index.vue')
}
]
export default routes;
修改main.js中VueRouter mode及增加监听beforeEach事件
//...省略
let instance = null
let router = null
/**
* 渲染函数
* 两种情况:主应用生命周期钩子中运行 / 微应用单独启动时运行
*/
function render() {
// 在 render 中创建 VueRouter,可以保证在卸载微应用时,移除 location 事件监听,防止事件污染
router = new VueRouter({
// 运行在主应用中时,添加路由命名空间 /vue
// base: window.__POWERED_BY_QIANKUN__ ? "/vue" : "/",
// mode: "history",
routes,
});
if (window.__POWERED_BY_QIANKUN__) {
router.beforeEach((to, from, next) => {
if (!to.path.includes("/microApp")) {
next({
path: "/microApp/vue" + (to.path == "/" ? "" : to.path)
})
} else {
next()
}
})
}
// 挂载应用
instance = new Vue({
router,
render: (h) => h(App),
}).$mount("#app")
}
// 独立运行时,直接挂载应用
if (!window.__POWERED_BY_QIANKUN__) {
render()
}
//...省略
3. React子应用改造
修改App.js
参考资料: