2

Micro front-end microApp practice

The concept of micro front-end was proposed by ThoughtWorks in 2016. It draws on the architectural concept of micro-services. The core is to split a huge front-end application into multiple independent and flexible small applications. Each application can be developed independently and independently. Run, deploy independently, and then integrate these small applications into a complete application, or integrate several applications that have been running for a long time and have no relationship into one application. The micro-frontend can not only integrate multiple projects into one, but also reduce the coupling between projects and improve the scalability of the project. Compared with a whole front-end warehouse, the front-end warehouse under the micro-frontend architecture tends to be smaller and more flexible.

Project renovation background

Because the project needs to be a big data fusion platform, the main functional modules include user management, process management, big data governance operator applications, basic components and other mixed integration platforms; the company currently has user management, process management and other finished products; basic The main content is also consistent with the functions of these products. The main frame only controls the navigation and header information; therefore, it is hoped to be able to integrate and access faster in a multiplexed manner.

Comparison of popular front-end microservice frameworks

parameter singlespa qianku microapp
Development costs high development cost development cost high development cost
maintenance cost middle middle middle
technology stack Unlimited technology stack Unlimited technology stack Unlimited technology stack
Ease of implementation difficult to achieve in progress Simple to implement
principle Listen for url change events Listen for url change events WebComponent

After comparison, I think micro-app is easy to use at present, and all functions are encapsulated into a WebComponent-like component, so that a micro-front-end application can be rendered by embedding a line of code in the base application. At the same time, micro-app also provides a series of complete functions such as js sandbox, style isolation, element isolation, preloading, data communication, and static resource completion. Sub-applications basically do not need too much project transformation, and the relative use cost is lower

Docking Instructions

  • Main framework dependency package introduction
 import microApp from '@micro-zoe/micro-app'
  • The main application starts (and can be configured globally)
 microApp.start({
  plugins: {
    global: [{
      loader(code, url, options) { // 必填
        console.log('全局插件')
        return code
      }
    }],
    }
  }
})

//Related parameters
microApp.start({
inline: true, // default false
destroy: true, // default false
disableScopecss: true, // default value false
disableSandbox: true, // default value false
shadowDOM: true, // default false
ssr: true, // default false
})

  • Configure the component node
 <micro-app
      style="height: 100%;"
        name='appnameUserCenter'
        :url='url'
        :data='microAppData'
        @created='handleCreate'
        @beforemount='handleBeforeMount'
        @mounted='handleMount'
        @unmount='handleUnmount'
        @error='handleError'
        @datachange='handleDataChange'
      ></micro-app>

life cycle list

  1. created
    Triggered after the <micro-app> tag is initialized and before the resource is loaded.
  2. beforemount
    Fired after loading the resource is complete, but before starting to render.
  3. mounted
    Fired after the sub-app rendering is complete.
  4. unmount
    Fired when the child app is uninstalled.
  5. error
    Triggered when the sub-app rendering error, only the error that will cause the rendering to terminate will trigger this life cycle.
  • Route matching settings (fuzzy matching, recommended main application history, micro application hash mode,)
 {
    path: '/mainPanel',
    name: 'mainPanel',
    component: mainPanel,
    children:[
      {
        path: '/mainPanel/dataCenter*',
        name: 'dataCenter',
        component:()=>dataCenter
      },
      {
        path: '/mainPanel/userCenter*',
        name: 'userCenter',
        component:()=>userCenter
      },
    ]
  }
  • Main Microframework Newsletter
 microMenu(appName, path, hash) {

            if (!getActiveApps().includes(appName)) {
   
                path = '/mainPanel' + path+'/'
                    // child-vite 和 child-react17子应用为hash路由,这里拼接一下hash值
                    hash && (path += `/#${hash}`)
                    // 主应用跳转
                    this.$router.push(path)
                } else {
           
                    let childPath = null
                    // child-vite 和 child-react17子应用是hash路由,hash值就是它的页面地址,这里单独处理
                    if (hash) {
                    childPath = hash
                    } else {
                    // path的值形式如:/app-vue2/page2,这里/app-vue2是子应用的基础路由,/page2才是页面地址,所以我们需要将/app-vue2部分删除
                    childPath = path.replace(/^\/app-[^/]+/, '')
                    !childPath && (childPath = '/') // 防止地址为空
                    }
                    // 主应用通过下发data数据控制子应用跳转
                    microApp.setData(appName, { path: childPath })
                }
        }
  • Microframework and its routing jump
 (function () {
  let app = null;
  //创建vue实例
  const createVue = function () {
    app = new Vue({
      el: "#app",
      router,
      store,
      render: (h) => h(App),
    });
  };
  // 与基座进行数据交互
  const handleMicroData = function (callBack) {
    window.microApp.addDataListener((data) => {
      callBack(data);
    });
  };

  // 微前端环境下,注册mount和unmount方法
  if (window.__MICRO_APP_ENVIRONMENT__) {
    let {token} = window.microApp.getData();
    token && setToken(token);
    console.log("data-center token:", token);
    window[`micro-app-${window.__MICRO_APP_NAME__}`] = {
      //微前端挂载
      mount: () => {
        createVue();
        handleMicroData((data) => {
          //交互操作
          store.dispatch("settings/changeSetting", {
            key: "microFlag",
            value: true,
          });
          console.log("data-center addDataListener:", data);
          router.push(data.path);
        });
      },
      //微前端卸载
      unmount: () => {
        app.$destroy();
        app.$el.innerHTML = "";
        app = null;
        console.log("微应用child-vue2卸载了");
      },
    };
  } else {
    // 非微前端环境直接渲染
    createVue();
  }
})();

西安小哥
1.3k 声望88 粉丝

thinking、doing、do better、do much better than today。exchange 、sharing、improve as quickly as possible。