微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用baseHref正确构建带有i18n的Angular 6应用程序到“语言环境目录”?

我正在尝试以多种语言提供我的应用程序,并且我正在关注Angular的 i18n guide.认语言环境是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","i18nLocale": "fr","i18nMissingTranslation": "error"
    }
  }
},

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

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

1.)
该应用程序始终构建为dist / myapp而不是dist / myapp / fr或dist / myapp / es.

2.)
不使用baseHref参数,所以我不能简单地将构建移动到子目录,如/ dist / myapp / fr.

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

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

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

/en
/fr
/es

3.)
最后,lang属性未正确设置. index.html未更改,将始终显示

<html lang="en">

而不是< html lang =“es”>或者< html lang =“fr”>.

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

解决方法

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

你实际上需要为每种语言做一个构建.

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

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

"build": {
    "builder": "@angular-devkit/build-angular:browser","buildOptimizer": true
    },

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐