Skip to content

Instantly share code, notes, and snippets.

@davidnguyen11
Last active April 4, 2019 07:41
Show Gist options
  • Save davidnguyen11/0ab27a20f41cef8213b703463f13e6cc to your computer and use it in GitHub Desktop.
Save davidnguyen11/0ab27a20f41cef8213b703463f13e6cc to your computer and use it in GitHub Desktop.
const IntlMessageFormat = require('intl-messageformat');
var globalLocale: string = '';
export function getI18n({ messages }: I18nOptions): I18n {
return {
messages: () => getMessages(messages(globalLocale))
};
}
function getMessages(messages: Dictionary<string>): Dictionary<CallBackFunction> {
const result: Dictionary<CallBackFunction> = {};
Object.keys(messages).map((key: string) => {
result[key] = function(values: Dictionary<string>) {
const msg = new IntlMessageFormat(messages[key], globalLocale);
return msg.format(values);
};
});
return result;
}
export function setGlobalLocale(options: GlobalLocale) {
globalLocale = options.locale;
}
interface GlobalLocale {
locale: string;
}
interface I18n {
messages(): Dictionary<CallBackFunction>;
}
interface I18nOptions {
messages(locale: string): Dictionary<string>;
}
interface CallBackFunction {
(values: Dictionary<string>): void
}
interface Dictionary<T> {
[key: string]: T;
}

Prepare

Create directory locale. Create 3 files below.

index.ts

import { getI18n } from '../i18n';

export const i18n = getI18n({
  messages: locale => require(`./locale.${locale}.json`)
});

locale.en.json

{
  "greeting": "Hello",
  "lol": "hello {someone}. My name is {myName}"
}

locale.vi.json

{
  "greeting": "Xin chao",
  "lol": "chao {someone}. Ten toi la {myName}"
}

main app

import { setGlobalLocale } from 'i18n-wrapper';
import { i18n } from './locale';

setGlobalLocale({ locale: 'en' });
const { lol } = i18n.messages();
const lolContent = lol({ someone: 'John', myName: 'David' });
console.log(lolContent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment