Packaging an Angular library with i18n support

时间秒杀一切 提交于 2019-12-03 05:44:02

When you generate a translation file for the main app with the CLI (with ng xi18n), elements with the attribute i18n in the library are imported in the translation file. You can then define the translations in the main app.

There are two ways of doing so - statically providing the assets and bundling on build time or configuring translation path on runtime.

  1. In order to statically include files on build time, you just use setTranslations in the code, as mentioned in https://github.com/ngx-translate/core docs. Then, you can just bundle your translations with the code.

  2. Better would be to let consumer know what to use. In order to properly be able to provide path to translation files (assuming standard structure, where every translation is residing in a separate file containing language in the name), you can do something as follows:

    interface TranslationsConfig {
      prefix: string;
      suffix: string;
    }
    
    export const TRANSLATIONS_CONFIG = new InjectionToken('TRANSLATIONS_CONFIG');
    
    @NgModule({
      declarations: [],
      imports: [
        NgxTranslateModule,
      ],
      exports: [
        NgxTranslateModule,
      ]
    })
    export class TranslateModule {
      public static forRoot(config: TranslationsConfig): ModuleWithProviders {
        return {
          ngModule: TranslateModule,
          providers: [
            {
              provide: TRANSLATIONS_CONFIG,
              useValue: config
            },
            ...NgxTranslateModule.forRoot({
              loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient, TRANSLATIONS_CONFIG]
            }
          }).providers
        ],
      };
    }
    

    }

This code makes sure that when building library, AOT will be able to resolve types (hence InjectionToken etc.) and allows to create custom translations loader.

Now it's only up to you to implement loader factory or class that will use the config! This is mine (I'm using POs for my translations):

export function HttpLoaderFactory(http: HttpClient, config: TranslationsConfig) {
  return new TranslatePoHttpLoader(http, config.prefix, config.suffix);
}

Please do remember to export every class and function that you're using in the module as that's prerequisite for AOT (and libraries are built with AOT by default).

To use this whole solution, wherever you use your main library module or this translation module, you can just call TranslateModule.forRoot(/* Your config here */). If this is not the main module exported, more on using hierarchical modules with forRoot here:

How to use .forRoot() within feature modules hierarchy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!