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

Angular 15中用ng serve修改base href实现多路径同时启动应用

解决Angular 15多路径同时启动的方案

方案一:CLI配置+动态BASE_HREF注入(推荐)

1. 修改angular.json配置

在projects -> [你的项目名] -> architect -> serve -> configurations下新增两个配置项:

"site1": {
  "servePath": "/site1",
  "buildTarget": "[你的项目名]:build:site1"
},
"site2": {
  "servePath": "/site2",
  "buildTarget": "[你的项目名]:build:site2"
}

接着在projects -> [你的项目名] -> architect -> build -> configurations下对应添加:

"site1": {
  "baseHref": "/site1/"
},
"site2": {
  "baseHref": "/site2/"
}

2. 动态注入APP_BASE_HREF

在app.module.ts中通过依赖注入动态设置base href,无需修改index.html的<base href='/' />标签:

import { NgModule, APP_BASE_HREF } from '@angular/core';

@NgModule({
  providers: [
    { 
      provide: APP_BASE_HREF, 
      useValue: window.location.pathname.split('/')[1] || '/' 
    }
  ]
})
export class AppModule { }

Angular会自动根据当前访问路径识别base href,配合CLI配置确保资源加载和路由正常。

3. 启动双服务

打开两个终端,分别执行:

ng serve --configuration site1
ng serve --configuration site2

现在可同时访问http://localhost:4200/site1和http://localhost:4200/site2,热更新各自独立,资源加载无异常。

方案二:代理配置映射路径(简易场景)

如果不想修改代码,可通过代理将不同路径映射到同一服务实例,但路由需额外适配:

1. 创建proxy.conf.json

{
  "/site1/*": {
    "target": "http://localhost:4200",
    "pathRewrite": {"^/site1": ""},
    "changeOrigin": true
  },
  "/site2/*": {
    "target": "http://localhost:4200",
    "pathRewrite": {"^/site2": ""},
    "changeOrigin": true
  }
}

2. 启动服务时指定代理

ng serve --proxy-config proxy.conf.json

注:此方式需在路由模块中添加前缀适配逻辑,仅适合无复杂路由的简单项目。

关键说明

Angular 15中ng serve的--serve-path仅控制访问路径前缀,资源加载依赖baseHref。方案一完全遵循官方规范,支持双服务独立运行,是更可靠的解决方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:30:16