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

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 {}

You can find a complete working example using Nx here.

Last updated

Was this helpful?