Skip to content
On this page

2022-10-umi的运行时配置

1. 需求场景

有一些路由不希望一开始就配置在路由的json文件上,希望请求完用户的权限之后,再对应的添加路由。 为了解决这个问题,查看了umi的问题,发现了umi的运行时配置 https://umijs.org/docs/api/runtime-config

2. 运行时配置说明

是在浏览器端执行,不要引入node。约定 src/app.tsx 为运行时配置。

3. onRouteChange({ routes, matchedRoutes, location, action })

在初始加载和路由切换时做一些事情。 比如用于做埋点统计,

tsx
export function onRouteChange({ location, routes, action }) {
  bacon(location.pathname);
}

比如用于设置标题,

tsx
import { matchRoutes } from 'umi'
 
export function onRouteChange({ clientRoutes, location }) {
  const route = matchRoutes(clientRoutes, location.pathname)?.pop()?.route
  if (route) {
    document.title = route.title || '';
  }
}

4. render(oldRender: Function)

覆写 render。 比如用于渲染之前做权限校验,

tsx
import { history } from 'umi';

export function render(oldRender) {
  fetch('/api/auth').then(auth => {
    if (auth.isLogin) { oldRender() }
    else { 
      history.push('/login'); 
      oldRender()
    }
  });
}

5. patchClientRoutes

修改路由。 比如在最前面添加一个 /foo 路由,

tsx
import Page from '@/extraRoutes/foo';
 
export function patchClientRoutes({ routes }) {
  routes.unshift({
    path: '/foo',
    element: <Page />,
  });
}

不过一般都是需要接口请求完路由信息才增加路由,这个需要结合render实现

tsx
let extraRoutes;
 
export function patchClientRoutes({ routes }) {
  // 根据 extraRoutes 对 routes 做一些修改
  patch(routes, extraRoutes);
}
 
export function render(oldRender) {
  fetch('/api/routes')
    .then((res) => res.json())
    .then((res) => {
      extraRoutes = res.routes;
      oldRender();
    });
}

这里的patch只的是要自己根据自己的实际需求,合并处理routes。不是一个确定的方法,所以没写从哪里引用。

注意:直接修改 routes,不需要返回

Released under the MIT License.