translations.ts
May 6, 2021•332 words
// i18n-react configuration - utils/translations.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import errorHandler from '@utils/error-handler';
// Here, import all language locals. Then add each namespace to the ns constant below
import 'assets/locales/en-GB/core.json';
import 'assets/locales/fr/core.json';
// Note: By default i18n grabs translations from assets/locales/[lan]/**.json
// Docs for config params: https://www.i18next.com/overview/configuration-options
// And the full i18next API: https://www.i18next.com/overview/api
// Below is the I18Next global configuration
// The Backend plugin is used to load language files with XHR
// The LanguageDetector plugin is the most through approach to detecting users language
const fallbackLng = 'en-GB';
const debugMode = process.env.NODE_ENV === 'development'; // Check if in dev or prod
const nameSpaces = ['core', 'test-translations']; // Add all new namespaces here first
const defaultNS = 'core'; // We set the default namespace to 'core' for the app scaffold
// Function is called if an attempt to access a key that couldn't be found
// It is important to keep track of this, so it can be fixed
const missingKeyHandler = (langs: string[], ns: string, key: string, fbVal: string) => {
const errorDescription =
`Translation Error: Key '${key}' was not found ` +
`in namespace '${ns}' using languages '${langs}' with a fallback of '${fbVal}'`;
errorHandler(errorDescription, 'Translation Module');
};
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng,
debug: debugMode,
ns: nameSpaces,
defaultNS,
interpolation: {
escapeValue: false, // In React escapes happen by default
},
preload: [fallbackLng], // Pre-load the default lang for SSR
saveMissing: true,
missingKeyHandler, // Handle missing keys
});
export default i18n;
// i18n helper functions - utils/trans-helpers.ts
/* eslint-disable import/prefer-default-export */
import { TFunctionResult, TOptions } from 'i18next';
import { useTranslation } from 'react-i18next';
interface TPrefixFunction {
<TResult extends TFunctionResult = string>(key: string, options?: TOptions | string): TResult;
}
export const usePrefixTranslation = (prefix: string, ns?: string) => {
const { t } = useTranslation(ns);
const tp: TPrefixFunction = (key: string, options?: TOptions | string) =>
t(`${prefix}.${key}`, options);
return { tp, t };
};