I'm doing some tests with Angular CLI version 1.0.0-beta.19-3, which installs and uses Angular 2.1.0. As you probably know, Angular-cli is using Webpack.
I tried to configure i18n module by following the procedure step by step in the Angular 2 Cookbook. The only hiccup is that the procedure is using a System.JS near the end for the XLIFF files merge.
I don't know how to handle that part of the procedure since Angular CLI is using Webpack, not systemJS.
I got stuck there too and made something work which of course I would not consider 'final' but good enough for a proof of concept implementation:
SystemJS Text-Plugin not necessary (as we use Webpack and not SystemJS)
Also we do not use an alternative for this plugin. (There is a plugin for webpack but unfortunately we cannot configure webpack currently with angular-cli) Instead we just re-write the .xlf-Files to .ts-Files manually. Each translation file looks something like this.
Example messages.fr.ts:
export const Translation = `
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="ng2.template">
<body>
...
</body>
</file>
</xliff>
`;
i18n-providers.ts has to be adapted like this:
import { TRANSLATIONS, TRANSLATIONS_FORMAT, LOCALE_ID } from '@angular/core';
declare var System: any;
interface TranslationFileContent {
Translation: string;
}
export function getTranslationProviders(): Promise<Object[]> {
// Set your locale here or get it from somewhere (e.g. localStorage)
let locale: string = 'fr';
const noProviders: Object[] = [];
switch (locale) {
case 'fr':
return System.import('./messages.fr.ts')
.then( (translations: TranslationFileContent ) => {
return createProviders(translations, locale);
})
.catch(() => noProviders);
// Add additional languages here
default:
return Promise.resolve(noProviders);
}
}
function createProviders(translations: TranslationFileContent, locale: string) {
return [
{ provide: TRANSLATIONS, useValue: translations.Translation },
{ provide: TRANSLATIONS_FORMAT, useValue: 'xlf' },
{ provide: LOCALE_ID, useValue: locale }
];
}
If you are surprised about the switch-case... Webpack will only bundle files which it can readout from the files so something like System.import('./messages.' + locale + '.ts'); did not work for me. If you find something feel free to add this here as a comment.
main.ts is the same as in the angular cookbook for i18n
Regarding JiT (Just-in-Time) vs. AoT (Ahead-of-Time) compilation: The solution above is for JiT. I had another solution for AoT (which was actually simpler) but no solution (Project setup) that worked for both at he same time.
Hope this helped (and answer came not too late).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With