从打字稿中提取 $localize 消息在 Angular 9 中不起作用

Extracting $localize messages from typescript not working in Angular 9

到目前为止我知道我可以通过 ng xi18n 提取 i18n 消息(来自 html)。但我也有一些需要翻译的打字稿文本。我像这样使用 $localize:$localize':@@info:It's green!'。如果我 运行 ng xi18n,它不会使用 $localize 提取文本。 我正在使用 Angular 9。也许这个功能只适用于 Angular 10?如果是这样,运行使用 xi18n 命令会成功吗?

整个新更新仍然有些未记录,但对于 ng xi18n,您现在需要添加 --ivy

最终这甚至不应该再使用 xlf 文件,而是作为对象映射加载到 polyfill 中(虽然尚未自动完成提取到该形式的操作)。

因为您的应用已启用本地化 (ng add @angular/localize) 然后 在您应用的 angular.json 文件中,您可以将 "ivy":true 添加到 extract-i18n 属性下的选项中,如下所示: “提取国际化”:{ "建造者": "@angular-devkit/build-angular:extract-i18n", “选项”: { "browserTarget": "commons-admin:build", “常春藤”:是的 } } 然后你会看到 i18n-extraction 不仅提取了 HTML 文件,还提取了使用 $localize 格式的 *.ts 文件。

即使使用 angular cli v10,我也遇到了同样的问题。我尝试使用 --ivy 选项,但我遇到了同样的问题。 我找到了一个解决方法:因为只有提取到 xlf 文件不起作用,但是 build:prod 之后的翻译即使对于 ts 文件中的 $localize 也很有效,当我有一些东西要翻译时,这只是在 ts 文件中,我在我从未显示的 ng-container 中的组件的 html 文件中添加了要翻译的词。 然后就和往常一样,当我运行 ng xi18n 的时候,我可以在xlf文件中找到我需要的词并进行翻译。

html 文件:

<!-- my regular content -->
<p> this is the regular content of my html file</p>

<!-- The words in my ts files I need to translate with
displayi18n always to "false" so it is never displayed-->
<ng-container *ngIf="displayi18n">
  <span i18n="@@settings">Paramètres</span>
  <span i18n="@@users">Utilisateurs</span>
</ng-container>

在我的 ts 文件中:

@Component ...
export class MyComponent ...
  ...
  // Var to tell ngIf to not display the ng-container for i18n
  public displayi18n: boolean = false;
  
  // Where I need the translated words:
  public settings_label: string = $localize`:@@settings:Paramètres`
  public users_label: string = $localize`:@@users:Utilisateurs`
  ...