Angular 6 and i18n in typescript

后端 未结 4 1041
半阙折子戏
半阙折子戏 2021-01-05 15:51

I saw that angular6 implements i18n for its components and that by using i18n you can internationalize your html but can you do the same with typescript? I have two specific

4条回答
  •  半阙折子戏
    2021-01-05 16:08

    This is not possible through the library's API until now (@angular/language-service v7.2).

    Below is my workaround (thank fredrikredflag for his good post on GitHub and thank @BrunoBruzzano for the link):


    src/app/i18n.service.ts:

    import {Injectable} from "@angular/core";
    import {Xliff2} from '@angular/compiler';
    // You can also import {Xliff} or {Xtb} instead of {Xliff2}, depending on your project configurations
    
    declare const require;
    const content = require('raw-loader!../i18n/messages.fa.xlf');
    
    @Injectable({
        providedIn: 'root'
    })
    export class I18nService {
        private readonly xliff: any = new Xliff2().load(content, '');
    
        get(key: string): string {
            return this.xliff.i18nNodesByMsgId[key][0].value;
        }
    }
    

    i18n pseudo-component (JUST FOR AUTO-GENERATING TRANSLATIONS in messages.xlf file):

    1. src/app/i18n/i18n.component.ts (Isn't important. Just needed to exists.):

      import {Component} from '@angular/core';
      @Component({templateUrl: './i18n.component.html'})
      export class I18nComponent {}
      
    2. src/app/i18n/i18n.component.html (don't forget using an id!)

      New version available. Load New Version?

    Don't forget declaring I18nComponent in your @NgModule.


    Usage (after running ng xi18n ... and translating):

    In your component:

    ...
    import {I18nService} from './i18n.service';
    
    ...
        constructor(private i18nService: I18nService, ...) { ... }
    
        sampleUsage() {
            confirm(this.t('newVersionAlert'));
        }
    
        /**
         * translate
         */
        private t(i18nId: string) {
            return this.i18nService.get(i18nId);
        }
    ...
    

    Utility script to translate i18n.service.ts before build:

    (This requirement: require('raw-loader!../i18n/messages.fa.xlf') needs to be translated to match wanted locale.)

    PreBuild/prebuild.ts:

    import {Xliff2} from "@angular/compiler";  
    // You can also import {Xliff} or {Xtb} from "@angular/compiler" depending of your case.
    
    const fs = require('fs');  
    const path = require('path');  
    
    const localeId = process.argv[2];  
    
    if (localeId === undefined) throw new Error(`No language specified.\nUsage: node ${path.basename(__filename)} '}`);  
    
    const content = fs.readFileSync(`src/i18n/messages.${localeId}.xlf`, 'utf8');  
    const xliff = new Xliff2().load(content, '');
    
    const i18nServiceFilePath = './src/app/i18n.service.ts'; 
    
    fs.writeFileSync(i18nServiceFilePath,  
      fs.readFileSync(i18nServiceFilePath, 'utf8')  
        .replace(/(raw-loader!\.\.\/i18n\/messages\.)\w{2}(\.xlf)/, `$1${xliff.locale}$2`)  
    );
    

    PreBuild/tsconfig.json:

    {
        "compilerOptions": {
            "outDir": "./build",
            "lib": [
                "es2018",
                "dom"
            ],
            "module": "commonjs",
            "moduleResolution": "node",
            "target": "es6",
            "typeRoots": [
                "../node_modules/@types"
            ]
        },
        "files": [
            "prebuild.ts"
        ]
    }
    

    package.json:

    ...
    "scripts": {
        "compile-pre-build": "tsc -p PreBuild/tsconfig.json --pretty",
        "pre-build": "node PreBuild/build/prebuild.js",
        ...
    ...
    

    Usage:

    (After one-time npm run compile-pre-build:)

    npm run pre-build -- fa
    

    or

    npm run pre-build -- en
    

    This will edit i18n.service.ts.

提交回复
热议问题