首页 > 解决方案 > Angular i18n AOT 编译 - 使用 nginx 的 CI 部署与使用 ng serve 的本地开发

问题描述

我目前正在开发一个包含 i18n 的 Angular 8 应用程序。我选择了使用 2 个并行运行的独立构建/应用程序的 AOT 方法。其中一个是en,另一个de

对于 CI,我有一个管道,它使用 Dockerfile 来构建 2 个不同的构建配置,并将它们放在彼此相邻的 2 个文件夹中。在 2 个 Angular 应用程序前面,我有 nginx 根据 URL 重定向到它们各自的语言文件夹。

Dockerfile:

RUN yarn ng build frontend --configuration=en
RUN yarn ng build frontend --configuration=de

示例:当我在 下访问我的 CI 部署myapp.com/en时,nginx 访问该文件en夹下的应用程序的索引文件。

Nginx 配置:

  location / {
    try_files $uri$args /en/index.html;
  }
  location /en/ {
    alias /usr/share/nginx/html/en/;
    try_files $uri$args $uri$args/ /en/index.html;
  }
  location /de/ {
    alias /usr/share/nginx/html/de/;
    try_files $uri$args $uri$args/ /de/index.html;
  }

这一切都很好,而且效果很好,但现在是实际问题:

对于本地开发,我仍然希望能够使用类似的设置,其中我有两个单独的 AOT 编译的应用程序版本,但我正在寻找一种不使用 nginx 进行本地开发设置的方法。

有没有办法在以某种形式使用时实现类似的 i18n 应用程序结构ng serve -c <locale>

我知道我可以使用 nginx 在本地进行基本相同的设置并重定向到正确的文件夹,但如果可能的话,我不想这样做,因此我不需要单独的 docker 设置(我还有很多其他的我不想在本地运行的 Dockerfile 中的东西)。

标签: angulardockerinternationalizationcontinuous-integrationangular-i18n

解决方案


您可以将以下内容添加到您的angular.json:(
您可能已经有了构建配置,只需相应browserTarget地调整serve-configuration

angular.json

"build": {
  ...
  "configurations": {
    ...
    "en": {
      "aot": true,
      "baseHref": "/en/"
      "outputPath": "dist/en/",
      "i18nFile": "src/locale/messages.en.xlf",
      "i18nFormat": "xlf",
      "i18nLocale": "en",
      ...
    }
    /* same for "de" with different params */
  }
},
"serve": {
  ...
  "configurations": {
    "en": { "port": 4201, "browserTarget": "*project-name*:build:en" },
    "de": { "port": 4202, "browserTarget": "*project-name*:build:de" }
    ...
  }
}

运行ng s -c=en或将以下内容添加到您的package.json

"scripts" : {
  "serve-en": "ng serve --configuration=en",
  "serve-de": "ng serve --configuration=de",
  ...
}

该站点将在http://localhost:4200/en/下提供服务。/de除了or之外的任何其他路径/en都会引发GET-error。(您的配置可能会有所不同)

这将像构建应用程序一样构建应用程序ng serve,只需使用构建配置(使用 i18n)。这在重新编译时可能会很慢,因此您可能希望创建一个单独的配置来为您的应用程序提供服务(没有构建优化等。也许baseHref="/")。

查看官方文档:https ://angular.io/guide/i18n#merge-with-the-aot-compiler


要添加到您的评论:

以下将使用默认构建选项,默认情况下应禁用优化。(端口在服务配置中设置)构建配置"buildTarget": "project:build:en-serve"

"architect": {
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "outputPath": "dist/**project-name**",
        "index": "src/index.html",
        "main": "src/main.ts",
        "baseHref": "/",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "src/tsconfig.app.json",
        "assets": [...],
        "styles": [...]
      },
      "configurations": {
        "en-serve": {
          "aot": true,
          "i18nLocale": "en",
          "outputPath": "dist/en",
          "i18nFile": "src/locale/messages.en.xlf",
          "i18nFormat": "xlf",
          "i18nMissingTranslation": "warn"
        },
       "other configs" ...
      }
    }
  }


推荐阅读