Skip to content

Instantly share code, notes, and snippets.

@egorguscha
Created October 8, 2020 09:51
Show Gist options
  • Save egorguscha/9ad693fe5dc8775d2360dca6cf346435 to your computer and use it in GitHub Desktop.
Save egorguscha/9ad693fe5dc8775d2360dca6cf346435 to your computer and use it in GitHub Desktop.
import { I18nTypes } from './I18nTypes';
const lang = 'en';
interface Langs {
[key: string]: string | string[];
}
/*tslint:disable:no-var-requires*/
const langs: Langs = require(`./langs/${lang}.json`);
export const i18n = (key: I18nTypes, index: number = 0, ...replacements: string[]): string => {
let value = langs[key];
value = Array.isArray(value) ? value[index] : value;
if (replacements.length) {
let i = 0;
const replaceFn = () => replacements[i++];
value = value.replace(/{(.*?)}/gim, replaceFn);
}
// empty string could be provided value as well
if (value === undefined && (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test')) {
console.warn(`Could not find translation by provided key: ${key}`);
}
return value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment