微应用没有挂载成功

背景

主应用部署的目录为portal,子应用部署目录为sub/sub-child
独立访问方式:

  • 主应用:http:xxx.com/portal
  • 子应用:http:xxx.com/sub/sub-child

解决思路

主应用和子应用分别部署在非根目录下,qiankun需要主应用与子应用路由一致,否则子应用就无法挂载成功,由于主应用自动添加了base,所以子应用需要与其一致,使用umi4中的提供的方法,从主应用将basename传递过来,然后子应用在运行时将它加到base中。

主应用的配置修改为:

// config/config.ts
const { UMI_ENV } = process.env;

export default defineConfig({
  base: UMI_ENV === 'dev' ? '/' : '/portal',
}

主应用的入口文件修改为:

// app.tsx
export const qiankun = api.getxxx().then(({ data }) => {
  return {
    apps: [
      {
        name: 'child',
        entry: CurrentEnvironment === 'dev' ? '//localhost:8000' : 'http://xxx.com/sub/sub-child',
        props: { basename: UMI_ENV === "dev" ? "" : "/portal" }, // 将basename传递给子应用
      },
    ],
})

子应用的入口文件修改为:

// app.tsx
import { createHistory } from '@umijs/max'; // umi3提供的方法是setCreateHistoryOptions

export const qiankun = {
  // 应用加载之前
  async bootstrap(props: any) {
    const basename = props?.basename;
    if (basename) createHistory({ basename });
  },
};

另外,还需要path保持一致,在子应用中也会自动加一个base,比如,子应用的base是/sub/sub-child/,那么,就意味着子应用的根目录是/sub/sub-child/,在主应用中使用时,引入的子应用路由地址就应该是/sub/sub-child/
子应用的配置修改为:

// config/config.ts
const { NODE_ENV } = process.env;

export default defineConfig({
  base: NODE_ENV === 'development' ? '/' : '/sub/sub-child/',
}

修改主应用路由:

// config/routes.ts
export default [
  {
    path: '/sub/sub-child',
    name: '一级子应用',
    microApp: 'triage',
    microAppProps: {
      autoCaptureError: true,
      autoSetLoading: true,
    },
  },
  {
    path: '/sub/sub-child/exp',
    name: '二级子应用',
    microApp: 'triage',
    microAppProps: {
      autoCaptureError: true,
      autoSetLoading: true,
    },
  },
]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容