打包支持i18n的Angular库

时间:2018-03-15 14:42:00

标签: angular localization internationalization ng-packagr

Angular的i18n很棒,像ng-packagr这样的工具使组件库打包变得非常简单,但它们可以合并吗?

如果我想打包和分发具有可翻译组件的组件库,该怎么办?可能吗?我如何打包这样的库?翻译文件是否与包一起发货,还是应该在主应用程序中定义?

如果有人能指出我的某些文件,那就太好了。 感谢

2 个答案:

答案 0 :(得分:2)

使用CLI(使用ng xi18n)为主应用程序生成翻译文件时,库中具有属性i18n的元素将导入到翻译文件中。然后,您可以在主应用程序中定义翻译。

答案 1 :(得分:0)

有两种方法-静态提供资产并在构建时捆绑或在运行时配置转换路径。

  1. 为了在构建时静态包含文件,您只需在代码中使用setTranslations,如https://github.com/ngx-translate/core文档中所述。然后,您可以将翻译与代码捆绑在一起。

  2. 更好的办法是让消费者知道使用什么。为了正确地提供翻译文件的路径(假设采用标准结构,其中每个翻译都驻留在名称中包含语言的单独文件中),您可以执行以下操作:

    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
        ],
      };
    }
    

    }

此代码确保在构建库时,AOT能够解析类型(因此InjectionToken等)并允许创建自定义翻译加载器。

现在,只有您才能实现将使用配置的加载程序工厂或类!这是我的(我在翻译中使用的是PO):

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

请记住要导出模块中使用的每个类和函数,因为这是AOT的先决条件(默认情况下,库是使用AOT构建的。)

要使用整个解决方案,无论在哪里使用主库模块或此翻译模块,都可以调用TranslateModule.forRoot(/* Your config here */)。如果这不是导出的主要模块,请在此处进一步使用带有forRoot的分层模块:

How to use .forRoot() within feature modules hierarchy

相关问题