Skip to content

Commit 122f858

Browse files
authored
Howto write a HashTranslateLoader
In issue ngx-translate#25 @mlegenhausen pointed out a solution that shows a very common use-case for a custom TranslateLoader implementation. Maybe we can extend the readme to show this (and maybe other use-cases in the future)? Kind regards :)
1 parent 4f95eb6 commit 122f858

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

README.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,47 @@ export function HttpLoaderFactory(http: HttpClient) {
6969
```
7070

7171
For now this loader only support the json format.
72+
73+
## Custom TranslateLoader strategies
74+
### HashTranslateLoader - Hashing translation files with angular-cli, webpack and SystemJS
75+
Allow caching of translation files by the browser could help to speed up the initial load of your app but with the default setup your translation files could miss the latest changes because the cache doesn't have the latest version of your translation file yet.
76+
77+
When using the angular-cli (uses webpack under the hood) you can write your own `TranslateLoader` that always loads the latest translation file available during your application build.
78+
79+
```typescript
80+
// webpack-translate-loader.ts
81+
import { TranslateLoader } from '@ngx-translate/core';
82+
import { Observable } from 'rxjs/Observable';
83+
84+
export class HashTranslateLoader implements TranslateLoader {
85+
getTranslation(lang: string): Observable<any> {
86+
return Observable.fromPromise(System.import(`../assets/i18n/${lang}.json`));
87+
}
88+
}
89+
```
90+
91+
When your project cannot find `System` then adding this to your `typings.d.ts` file helps:
92+
```typescript
93+
declare var System: System;
94+
interface System {
95+
import(request: string): Promise<any>;
96+
}
97+
```
98+
99+
Now you can use the `HashTranslateLoader` with your `app.module`:
100+
```typescript
101+
@NgModule({
102+
bootstrap: [AppComponent],
103+
imports: [
104+
TranslateModule.forRoot({
105+
loader: {
106+
provide: TranslateLoader,
107+
useClass: HashTranslateLoader
108+
}
109+
})
110+
]
111+
})
112+
export class AppModule { }
113+
```
114+
115+
One disadvantage of this solution is that you have to rebuild your application when there are only changes inside your language files.

0 commit comments

Comments
 (0)