There are two ways of doing so - statically providing the assets and bundling on build time or configuring translation path on runtime.
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.
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