You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Angular应用同时作为微前端子应用与独立应用运行?

解决Angular single-spa应用同时作为微前端子应用和独立应用运行的问题

当然可以实现。Angular single-spa应用默认是为微前端场景构建的,直接访问独立地址会空白,是因为它没有触发常规Angular应用的启动逻辑。只需做以下配置调整,就能让它同时支持两种运行模式:

1. 修改main.ts,添加环境判断逻辑

原来的main.ts可能仅注册了single-spa子应用,现在需要判断当前是否处于微前端环境,分别执行不同的启动逻辑:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { singleSpaAngular, getSingleSpaExtraProviders } from 'single-spa-angular';
import { Router } from '@angular/router';

if (environment.production) {
  enableProdMode();
}

// 判断是否处于微前端环境:检查window上的single-spa标识,或路径是否包含子应用前缀
const isSingleSpaEnv = window.singleSpaNavigate || window.location.pathname.startsWith('/app1');

if (isSingleSpaEnv) {
  // 微前端模式:注册single-spa子应用
  const lifecycles = singleSpaAngular({
    bootstrapFunction: () => platformBrowserDynamic(getSingleSpaExtraProviders()).bootstrapModule(AppModule),
    template: '<app-root></app-root>',
    Router,
  });

  export const bootstrap = lifecycles.bootstrap;
  export const mount = lifecycles.mount;
  export const unmount = lifecycles.unmount;
} else {
  // 独立模式:启动常规Angular应用
  platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err => console.error(err));
}

2. 调整路由配置,适配两种模式的路径前缀

修改app-routing.module.ts,让路由能根据运行环境自动切换基础路径:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';

// 动态获取基础路径:微前端模式用/app1,独立模式用/
const getBaseHref = () => {
  const singleSpaProps = (window as any).__SINGLE_SPA_PROPS__;
  return singleSpaProps?.baseHref || '/';
};

const routes: Routes = [
  { path: '', component: HomeComponent },
  // 其他路由配置...
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    baseHref: getBaseHref(),
    initialNavigation: 'enabledBlocking'
  })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

3. 动态设置index.html的base标签

将index.html中固定的base标签改成动态生成,适配两种模式:

<!-- 替换原来的<base href="/"> -->
<script>
  const baseHref = window.singleSpaNavigate ? '/app1/' : '/';
  document.write(`<base href="${baseHref}">`);
</script>

4. 测试验证

  • 启动Root Config(localhost:9000),访问localhost:9000/app1,确认微前端模式正常显示
  • 启动Angular应用(localhost:4200),直接访问localhost:4200,确认独立模式正常渲染

内容的提问来源于stack exchange,提问作者Huaxin Zhang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:42:41