微前端架构,嗯,听上去感觉不错。试用了下qiankun,并且看看他是如何实现的。
import { registerMicroApps, runAfterFirstMounted, setDefaultMountApp, start } from 'qiankun' export default { name: 'master', data () { return { apps: [ { name: 'slave', entry: '//localhost:8081', container: '#appContainer', activeRule: '/slave' } ] } }, created () { if (!window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__) { this.initQiankun() } else { // fix hot-reload location.reload() } }, methods: { goto (title, href) { window.history.pushState({}, title, href) }, initQiankun () { registerMicroApps( this.apps, { beforeLoad: [ app => { // eslint-disable-next-line no-console console.log('before load', app) } ], beforeMount: [ app => { // eslint-disable-next-line no-console console.log('before mount', app) } ], afterUnmount: [ app => { // eslint-disable-next-line no-console console.log('after unload', app) } ] } ) setDefaultMountApp('/slave') runAfterFirstMounted(() => { // eslint-disable-next-line no-console console.info('first app mounted') }) start({ prefetch: true }) } } }喵一喵这个registerMicroApps方法:
export function registerMicroApps<T extends object = {}>( apps: Array<RegistrableApp<T>>, lifeCycles?: FrameworkLifeCycles<T>, ) { // Each app only needs to be registered once const unregisteredApps = apps.filter(app => !microApps.some(registeredApp => registeredApp.name === app.name)); microApps = [...microApps, ...unregisteredApps]; unregisteredApps.forEach(app => { const { name, activeRule, loader = noop, props, ...appConfig } = app; registerApplication({ name, app: async () => { loader(true); await frameworkStartedDefer.promise; const { mount, ...otherMicroAppConfigs } = await loadApp( { name, props, ...appConfig }, frameworkConfiguration, lifeCycles, ); return { mount: [async () => loader(true), ...toArray(mount), async () => loader(false)], ...otherMicroAppConfigs, }; }, activeWhen: activeRule, customProps: props, }); }); }调用了registerApplication方法,用到了single-spa这个库,这个库是干啥的?从官网查了下:
single-spa is a framework for bringing together multiple JavaScript microfrontends in a frontend application. Architecting your frontend using single-spa enables many benefits, such as:
Use multiple frameworks on the same page without page refreshing (React, AngularJS, Angular, Ember, or whatever you're using)Deploy your microfrontends independentlyWrite code using a new framework, without rewriting your existing appLazy load code for improved initial load time看得出single-spa主要功能就是解决多个微应用整合在一起的框架,那就着重看下single-spa,
