Search code examples
jsonangularngx-translate

Share ngx-translate translation files across multiple apps in a NX workspace


I have a NX workspace containing many angular (v13) applications, all of this applications are quite similar. I'm using ngx-translate (v13) to handle the multilanguage support, so currently i have 2 json files (ENG and DE) for each application.

This is really hard to maintain since even a small change in the translations will result in many files being modified.

My wish is to move the common part of the translation files to a library so that i still have 2 files per application but they only contains application specific translations and all the rest is in 2 files in the library.

Which is the best way to achieve this goal?


Solution

  • This is what i did:

    I created the translation files in the library (folder assets/i18n) and add this to the project.json of the app, under "build.options.assets"

    {
      "input": "libs/shared-components/src/lib/assets/i18n",
      "glob": "**/*.json",
      "output": "assets/i18n/core"
    }
    

    Using MultiTranslateHttpLoader is possible to load multiple translation files, so i add this to the app.module.ts

    export function HttpLoaderFactory(http: HttpClient) {
       return new MultiTranslateHttpLoader(http, [
         { prefix: 'assets/i18n/core/', suffix: '.json' },
         { prefix: '/assets/i18n/', suffix: '.json' },
       ]);
    }
    

    Note: the order in which files are loaded is important, if both files contain a key, the key from the second file will overwrite the key from the first one.

    I'm not sure if this is the best method to achieve this goal, but for me it's working.