前端单页应用微服务化解决方案7 - 静态数据共享

345 阅读2分钟

文章转发自 alili.tech

在前面的一些介绍,相信你对微前端已经有了一个相对完整的认知. 下面介绍一下,再开发过程中我的一些小技巧与处理方法.

动态入口

当有新的子模块会挂载到项目中的时候,在UI中肯定需要一个新的入口进入子模块的UI. 而这样一个入口,是需要动态生成的.

例如:图中左边的菜单,不应该是代码写死的.而是根据每个模块提供的数据自动生成的.

不然每次发布新的模块,我们都需要在最外面的这个框架修改代码.这样就谈不上什么独立部署了.

静态数据共享

想要达到上面所的效果,我们可以这样做.

// ~/common/menu.js

import { isUrl } from '../utils/utils'
let menuData = [
  {
    name: '模块1',
    icon: 'table',
    path: 'module1',
    rank: 1,
    children: [
      {
        name: 'Page1',
        path: 'page1',
      },
      {
        name: 'Page2',
        path: 'page2',
      },
      {
        name: 'Page3',
        path: 'page3',
      },
    ],
  }
]
let originParentPath = '/'
function formatter(data, parentPath = originParentPath, parentAuthority) {
    ...
}

// 在这里,我们对外导出 这个模块的菜单数据
export default menuData

// Store.js
import { createStore, combineReducers } from 'redux'
import menuDate from './common/menu'
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
...

// 我们拿到数据之后,用一个reducer函数返回我们的菜单数据.
function menu() {
  return menuDate
}

...


// 最终以Store.js对外导出我们的菜单数据,在注册的时候,每个应用都可以拿到这个数据了
export const storeInstance = createStore(combineReducers({ namespace: () => 'list', menu, render, to }))

当我们的Base模块,拿到所有子模块的菜单数据,把他们合并后,就可以渲染出正确的菜单了.

这只是一个小技巧,像这样的技巧足以帮助我们在代码中完成很多想不到的事情. 这里只是打开一个思路,后续还有更多的微前端小技巧相关的文章. 未完待续 ...

相关文章

前端单页应用微服务化解决方案1 - 思考

前端单页应用微服务化解决方案2 - Single-SPA

前端单页应用微服务化解决方案3 - 模块加载器

前端单页应用微服务化解决方案4 - 消息总线

前端单页应用微服务化解决方案5 - 路由分发

前端单页应用微服务化解决方案6 - 构建与部署

前端单页应用微服务化解决方案7 - 静态数据共享

前端单页应用微服务化解决方案8 - 二次构建

Demo

前端微服务化 Micro Frontend Demo

微前端模块加载器

微前端Base App示例源码

微前端子项目示例源码