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:
- 更新
angular.json的build配置,为每个语言环境添加baseHref和localize参数:
"projects": { "你的项目名称": { "architect": { "build": { "configurations": { "pt": { "baseHref": "/pt/", "localize": ["pt-BR"], "i18nMissingTranslation": "error" }, "en": { "baseHref": "/en/", "localize": ["en"], "i18nMissingTranslation": "error" } } },
- 同步更新
serve配置,关联对应的build目标:
"serve": { "configurations": { "pt": { "browserTarget": "你的项目名称:build:pt" }, "en": { "browserTarget": "你的项目名称:build:en" } } } } } }
- 简化
i18n节点配置,移除sourceLocale中的baseHref:
"i18n": { "sourceLocale": "pt-BR", "locales": { "en": "src/translation/messages-en.json" } }
验证
执行对应命令后,访问指定地址即可:
ng serve --configuration=pt→ 访问http://localhost:4200/ptng serve --configuration=en→ 访问http://localhost:4200/en
注意:不要在应用中手动注册APP_BASE_HREF令牌,否则会覆盖此处的baseHref配置;路由模块保持默认的useHash: false即可。
内容的提问来源于stack exchange,提问作者Hoiama Rodrigues
相关产品推荐
相关产品推荐

