使用UmiJS快速搭建微前端应用

228 阅读1分钟

记录一下使用UmiJS配置微前端的过程,方便以后查找。

配置主应用

// .umirc.ts
export default {
    qiankun: {
        master: {
            apps: [
                {
                    name: 'web-umi-sub-one',
                    entry: '//localhost:8001'
                },
                {
                    name: 'web-umi-sub-two',
                    entry: '//localhost:8002'
                }
            ]
        }
    },
    routes: [
        {
            path: '/',
            redirect: '/home',
        },
        {
            name: '主应用 首页',
            path: '/home',
            component: './Home',
        },
        {
            name: '子应用 一',
            path: '/web-umi-sub-one/',
            microApp: 'web-umi-sub-one',
            routes: [
                { name: '首页', path: 'home', component: './MicroComponent' },
                { name: 'Table', path: 'table', component: './MicroComponent' },
            ],
        },
        {
            name: '子应用 二',
            path: '/web-umi-sub-two/',
            microApp: 'web-umi-sub-two',
            routes: [
                { name: '首页', path: 'home', component: './MicroComponent' },
                { name: 'Table', path: 'table', component: './MicroComponent' },
            ],
        },
    ]
}

修改子应用

// .umirc.ts
export default {
    ...
    base: '/web-umi-sub-one/',
    publicPath: '/',
    history: { type: 'hash' },
    qiankun: {
        slave: {}
    }
}

// app.ts
export const layout = () => {
    return {
        ...
        headerRender: false,
        footerRender: false,
        menuRender: false,
        menuHeaderRender: false,
    }
}

  • 主应用qiankun配置中的name保持唯一即可,不强制要求统一格式。一般和子应用package.jsonname字段保持一致。
  • 主应用qiankun配置中的entry保持和子应用配置中的publicPath保持一致。要根据测试环境和正式环境区分域名哦。
  • MicroComponent是主应用中的一个空页面,没什么用,只是为了编译不报错,实际不加载。
  • 主应用routers里面的microApp字段要和qiankun配置项中的name对应起来。
  • 主应用routers里面的path字段要和子应用中的配置项中的base字段保持一致。
  • 如果项目使用Docker+nginx部署,只有主应用中的nginx配置生效,因此要把子应用中的代理配置也写一份到主应用中。
  • 子应用的publicPath在本地运行时,使用/,部署到测试环境或者正式环境时,要替换为对应的域名。例如://web-umi-sub-one.dev.domain.com/