首页 > 解决方案 > 如何正确地将带有 i18n 的 Angular 6 应用程序构建到带有 baseHref 的“语言环境目录”中?

问题描述

我正在尝试使我的应用程序以多种语言提供,并且我正在遵循 Angular 的i18n 指南。默认语言环境是en-US,还有法语fr和西班牙语es翻译。

这很好用ng serve --configuration=fr,例如在运行应用程序时。

现在我到了要构建应用程序的地方。我正在使用这个命令:

ng build --prod --build-optimizer --i18n-file src/locale/messages.es.xlf --i18n-format xlf --i18n-locale es

而且我也angular.json按照指南中的说明进行了更新:

"architect": {
  "build": {
    "builder": "@angular-devkit/build-angular:browser",
    "options": {
    "outputPath": "dist/myapp",
    },
    "configurations": {
      "production": {
        "fileReplacements": [
          {
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.prod.ts"
          }
        ],
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "aot": true,
        "extractLicenses": true,
        "vendorChunk": false,
        "buildOptimizer": true
      },
      "es": {
        "aot": true,
        "outputPath": "dist/myapp/es",
        "baseHref": "/es/",
        "i18nFile": "src/locale/messages.es.xlf",
        "i18nFormat": "xlf",
        "i18nLocale": "es",
        "i18nMissingTranslation": "error"
      },
      "fr": {
        "aot": true,
        "outputPath": "dist/myapp/fr",
        "baseHref": "/fr/",
        "i18nFile": "src/locale/messages.fr.xlf",
        "i18nFormat": "xlf",
        "i18nLocale": "fr",
        "i18nMissingTranslation": "error"
    }
  }
},

构建过程有效,我得到了应用程序的翻译版本。


不幸的是,有些事情不起作用:

1.)
该应用程序始终构建在dist/myapp而不是在dist/myapp/fror中dist/myapp/es

2.)
-baseHref参数没有被使用,所以我不能简单地将构建移动到一个子目录中,比如/dist/myapp/fr.

为了更清楚,运行后build我想要一个这样的文件夹结构:

/dist/myapp/en
/dist/myapp/fr
/dist/myapp/es

什么时候myapp是我的webroot,应该可以在浏览器中访问这些路由:

/en
/fr
/es

3.)
最后-lang属性设置不正确。index.html没有改变,总是会显示:

<html lang="en">

而不是<html lang="es">or <html lang="fr">


使这项工作正常工作缺少什么?

标签: angularinternationalizationangular6locale

解决方案


在进行构建时,您需要传递正确的配置。否则,它只会使用production配置

您实际上需要为每种语言进行一次构建。

ng build --configuration=fr
ng build --configuration=en
ng build --configuration=es

您可以为每个配置指定要使用的选项(aot,输出散列,...),也可以将其放在options设置中build

  "build": {
    "builder": "@angular-devkit/build-angular:browser",
    "options": {
    "outputPath": "dist/myapp",
     "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "aot": true,
        "extractLicenses": true,
        "vendorChunk": false,
        "buildOptimizer": true
    },

至于更改lang属性,根据this github issue,您必须手动进行

export class AppComponent {
  constructor(@Inject(DOCUMENT) doc: Document, @Inject(LOCALE_ID) locale: string, renderer: Renderer2) {
    renderer.setAttribute(doc.documentElement, 'lang', locale);
  }
}

推荐阅读