Skip to main content

Inline Loaders

When working on a feature module or a library (which is common in a monorepo environment), we may want to have the translation files inside the module folder and ship them together with it. To enable this feature, Transloco supports scope with inline loaders. We can pass the scope name and an inline loader that leverages Webpack import function to lazy load the local translation files.

Let's say we have the following Angular CLI project:

📦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/component, we can define a scope provider and pass an inline loader:

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

Note that when using an inline loader, the scope key is used as the alias.

Now we can translate our content using the scope we define:

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

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.