robisim74 / angular-l10n

Angular library to translate texts, dates and numbers
MIT License
380 stars 59 forks source link

Json file convertion to js chunk creates a sublevel: [lang]_default #346

Closed johaven closed 7 months ago

johaven commented 7 months ago

Versions Angular: 17.1.0 Angular-l10n: 16

Bug Translations are broken because a sublevel is created in the js version.

Original json file

{
  "Previous": "Précédent",
  "Done": "Terminé",
  "Sign-in to your account": "Connectez-vous à votre compte",
  "Wrong login or password": "Identifiant ou mot de passe incorrect"
}

Chunked js

var Previous = "Pr\xE9c\xE9dent";
var Done = "Termin\xE9";
var to = "vers";
var fr_default = {
  "Sign-in to your account": "Connectez-vous \xE0 votre compte",
  "Wrong login or password": "Identifiant ou mot de passe incorrect"
}
robisim74 commented 7 months ago

Hi @johaven,

I assume you are using dynamic import as in the recent documentation example (I remind you here that it is just an example: implemeting L10nTranslationLoader you can load the file in the way you prefer).

Angular v17 uses esbuild by default. In newer bundlers, such as esbuild, vite, and rollupjs, the return value of a dynamic import is a javascript object.

Now in your example, you are using keys that are valid in a json, but are not valid in a javascript object, because they are not valid variable names.

You have two alternatives: implement a different loader, or import and transform the files by yourself, like this:

import it from '../i18n/it-IT/app.json';
import en from '../i18n/en-US/app.json';

@Injectable() export class TranslationLoader implements L10nTranslationLoader {

  public get(language: string, provider: L10nProvider): Observable<{ [key: string]: any }> {
    let data: any;
    switch (language) {
      case 'it-IT':
        data = it;
        break;
      default:
        data = en;
        break;
    }
    return of(JSON.parse(JSON.stringify(data)));
  }
}

and add "resolveJsonModule": true in tsconfig.

Hope this helps!

johaven commented 7 months ago

@robisim74 thank you for your explanation :)