Inline Loaders

When working on a feature module or a library (a common practice in a monorepo environment), it's often useful to include translation files inside the module folder and package them alongside the module. To facilitate this, Transloco supports scopes with inline loaders. This feature allows you to specify a scope name and provide an inline loader that uses ESBuild/Webpack's import function to lazily load the local translation files.

For example, consider the following Angular CLI project structure:

๐Ÿ“ฆprojects โ”— ๐Ÿ“‚feature โ”ƒ โ”ฃ ๐Ÿ“‚src โ”ƒ โ”ƒ โ”ฃ ๐Ÿ“‚lib โ”ƒ โ”ƒ โ”ƒ โ”ฃ ๐Ÿ“‚i18n โ”ƒ โ”ƒ โ”ƒ โ”ƒ โ”ฃ en.json โ”ƒ โ”ƒ โ”ƒ โ”ƒ โ”— es.json โ”ƒ โ”ƒ โ”ƒ โ”ฃ feature.component.ts โ”ƒ โ”ƒ โ”ƒ โ”ฃ feature.routes.ts โ”ƒ โ”ƒ โ”ƒ โ”— feature.service.ts โ”ƒ โ”ƒ โ”ฃ public-api.ts ๐Ÿ“ฆsrc โ”ฃ ๐Ÿ“‚app โ”ƒ โ”ฃ app.routes.ts โ”ƒ โ”ฃ app.component.css โ”ƒ โ”ฃ app.component.html โ”ƒ โ”ฃ app.component.ts โ”ƒ โ”ฃ app.config.ts โ”ƒ โ”— transloco.loader.ts โ”ฃ ๐Ÿ“‚assets โ”ƒ โ”ฃ ๐Ÿ“‚i18n โ”ƒ โ”ƒ โ”ฃ en.json โ”ƒ โ”ƒ โ”— es.json

Inside the feature route or component, we can define a scope provider and pass an inline loader that dynamically loads translation files:

feature.routes.ts
export const loader = ['en', 'es'].reduce((acc, lang) => {
  acc[lang] = () => import(`../i18n/${lang}.json`);
  return acc;
}, {});

export const FEATURE_ROUTES: Route = {
  path: 'feature',
  loadComponent: () =>
    import('./feature.component').then((FeatureComponent) => FeatureComponent),
  providers: [
    provideTranslocoScope({
      scope: 'scopeName',
      loader,
    }),
  ],
};

When using an inline loader, the scope's key serves as the alias for the translation scope.

Now, you can translate the content using the defined scope:

feature.component.ts
@Component({
  selector: 'app-feature',
  template: ` 
    <ng-container *transloco="let t">
      <p>{{ t('scopeName.title') }}</p>
    </ng-container>`,
  imports: [TranslocoDirective],
})
export default class FeatureComponent {}

Note that following the Angular DI rules, it can be done either in a feature module that we lazy-loaded or at the component providers level.

You can find a complete working example using Nx here.

Last updated

@ 2024 Transloco