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

Angular 17中i18n的sourceLocale设置baseHref无效问题求助

Angular 17 默认语言baseHref不生效的解决方案

问题场景

需要实现:

  • 执行ng serve --configuration=pt时,应用路由前缀为/pt(访问地址http://localhost:4200/pt)
  • 执行ng serve --configuration=en时,应用路由前缀为/en(访问地址http://localhost:4200/en)

但当前angular.json中i18n.sourceLocale定义的baseHref无法生效,原配置如下:

"i18n": {
  "sourceLocale": {
    "baseHref": "/my-base-href/",
    "code": "pt-BR"
  },
  "locales": {
    "en": {
      "translation": "src/translation/messages-en.json",
      "baseHref": "en/"
    },
  }
}

解决方案

Angular 17 中sourceLocale的baseHref配置存在兼容性问题,需通过architect下的build和serve配置单独为每个语言环境指定baseHref:

  1. 更新angular.json的build配置,为每个语言环境添加baseHref和localize参数:
"projects": {
  "你的项目名称": {
    "architect": {
      "build": {
        "configurations": {
          "pt": {
            "baseHref": "/pt/",
            "localize": ["pt-BR"],
            "i18nMissingTranslation": "error"
          },
          "en": {
            "baseHref": "/en/",
            "localize": ["en"],
            "i18nMissingTranslation": "error"
          }
        }
      },
  1. 同步更新serve配置,关联对应的build目标:
"serve": {
        "configurations": {
          "pt": {
            "browserTarget": "你的项目名称:build:pt"
          },
          "en": {
            "browserTarget": "你的项目名称:build:en"
          }
        }
      }
    }
  }
}
  1. 简化i18n节点配置,移除sourceLocale中的baseHref:
"i18n": {
  "sourceLocale": "pt-BR",
  "locales": {
    "en": "src/translation/messages-en.json"
  }
}

验证

执行对应命令后,访问指定地址即可:

  • ng serve --configuration=pt → 访问http://localhost:4200/pt
  • ng serve --configuration=en → 访问http://localhost:4200/en

注意:不要在应用中手动注册APP_BASE_HREF令牌,否则会覆盖此处的baseHref配置;路由模块保持默认的useHash: false即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 21:20:02