微前端简单实用
微前端 qiankun:底层基于single-spa
浏览器的微服务,基座。不同管理不同部署
package.json 配置。
"workspaces": ["app/*","experiment/*"
]
基座注册使用registerMicroApps,开启start
简单举例
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('销毁后', '')}
})
子应用// 需要暴露协议文件
let history, routes, app
export async function bootstrap(){console.log('vue2 bootstrap', )
}
export async function mount(props){console.log('vue2 mount', )render(props)
}
export async function unmount(){console.log('vue2 mount', )history = nullroutes=nullapp=null
}
function render(props){}
vue中
需要放在mount中,加载的时候再去挂载,不能一上来就加载 new Vue
另外路由需要改的createRouter需要更改
生成的时候使用,卸载的时候清空
render(props={}){
history = createWebHistory('/vue')createRouter({history,routes})
app = createApp()
app.use(router).mount(props.container ? props.container.querySelector('#app'):'#app') // 这里挂载在哪,接收mount里面传递过来props.判断是自己来的还是接受过来的
}
bootstrap 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子,不会再重复触发 bootstrap。
通常我们可以在这里做一些全局变量的初始化,比如不会在 unmount 阶段被销毁的应用级别的缓存等
应用每次进入都会调用 mount 方法,通常我们在这里触发应用的渲染方法
qian kun渲染的时候给我门一个变量, window.POWERED_BY_QIANKUN
可以根据需要做判断
if (!window.POWERED_BY_QIANKUN) {
}
if (window.POWERED_BY_QIANKUN) {
}
react中配置
if (!window.__POWERED_BY_QIANKUN__) {ReactDOM.render(<App towerProps={{}} />, document.querySelector('#root'));
}if (window.__POWERED_BY_QIANKUN__) {// 动态设置 webpack publicPath,防止资源加载出错// eslint-disable-next-line no-undefwindow.__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
export async function bootstrap() {console.log('react app bootstraped');
}export async function mount(props){console.log('react app mount', )let {container} = props// const root = ReactDOM.createRoot(document.getElementById('root'));ReactDOM.render(<App />,document.getElementById(container?container.querySelector('#root'):'#root'));// render()
}// render(props)export async function unmount(props){ReactDOM.unmountComponentAtNode(props.container? props.container.querySelector('#root'): document.querySelector('#root'),);}