qiankun微前端

发布时间 2023-07-17 08:54:42作者: Cxymds

qiankun 是一个基于 single-spa微前端实现库,旨在帮助大家能更简单、无痛的构建一个生产可用微前端架构系统。

微前端是一种多个团队通过独立发布功能的方式来共同构建现代化 web 应用的技术手段及方法策略。

如何使用配置qiankun

1. 主应用

安装qiankun

$ yarn add qiankun # 或者 npm i qiankun -S

在主应用中注册微应用

import { registerMicroApps, start } from 'qiankun';

registerMicroApps([
  {
    name: 'react app', // app name registered
    entry: '//localhost:7100',
    container: '#yourContainer',
    activeRule: '/yourActiveRule',
  },
  {
    name: 'vue app',
    entry: { scripts: ['//localhost:7100/main.js'] },
    container: '#yourContainer2',
    activeRule: '/yourActiveRule2',
  },
]);

start();

也可以将qianlun的启动做一个封装

import { start, initGlobalState } from 'qiankun'

// 挂载qiankun
export const mountedQiankun = () => {
  if (!window.qiankunStarted) {
    window.qiankunStarted = true
    start({
      prefetch: 'all', // 开启预加载
      sandbox: {
        experimentalStyleIsolation: false
      }, 
    })
  }
}

// qiankun通信
const state = {
  theme: localStorage.getItem('theme') || 'dark',
  cacheViews: [],
  excludeViews: {}
}
//定义全局状态,并返回通信方法,建议在主应用使用,微应用通过 props 获取通信方法。
export const actions = initGlobalState(state) 

然后再需要启动的页面或者组件进行启动

onMounted(() => {
  mountedQiankun()
})

vite.config.js

import qiankun from 'vite-plugin-qiankun'

export default defineConfig(({ command, mode }) => {
  return {
    plugins: [
     qiankun('主应用', {
        useDevMode: true
      }),
    ],
  }
})

关于initGlobalState

​ 可以调用三个方法

  • onGlobalStateChange: 在当前应用监听全局状态,有变更触发 callback,fireImmediately = true 立即触发 callback
  • setGlobalState: 按一级属性设置全局状态,微应用中只能修改已存在的一级属性
  • offGlobalStateChange: 移除当前应用的状态监听,微应用 umount 时会默认调用
import { initGlobalState, MicroAppStateActions } from 'qiankun';

// 初始化 state
const actions: MicroAppStateActions = initGlobalState(state);

actions.onGlobalStateChange((state, prev) => {
  // state: 变更后的状态; prev 变更前的状态
  console.log(state, prev);
});
actions.setGlobalState(state);
actions.offGlobalStateChange();

2. 微应用

安装qiankun

$ yarn add qiankun # 或者 npm i qiankun -S

mian.js

import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'


let app = null
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  app = createApp(App)
  app.use(router).use(pinia).use(plugins).use(directives).mount('#app')
} else {
  renderWithQiankun({
    bootstrap() {
      console.log('加载微服务')
    },
    mount(props) {
      console.log('启动微服务')
      app = createApp(App)
      app
        .use(router)
        .use(pinia)
        .use(plugins)
        .use(directives)
        .mount(props.container ? props.container.querySelector('#app') : document.getElementById('app'))

      const appStore = useAppStore()
      const tagsStore = useTagStore()
      props.onGlobalStateChange(state => {
        appStore.theme = state.theme
        tagsStore.parentCacheViews = state.cacheViews
        tagsStore.excludeViews = state.excludeViews
      })
    },
    update() {
      console.log('update')
    },
    unmount() {
      console.log('卸载微服务')
      app.unmount()
    }
  })
}

vite.config.js

import qiankun from 'vite-plugin-qiankun'

export default defineConfig(({ command, mode }) => {
  return {
    plugins: [
      qiankun('注册的activeRule', {
        useDevMode: true
      }),
    ],
  }
})