Skip to content

Commit

Permalink
Refactor language importing
Browse files Browse the repository at this point in the history
  • Loading branch information
chimpdev committed Sep 14, 2024
1 parent 3b3a28e commit 5f1967c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,8 @@ To add a new language to the website, follow these steps:

1. Create a new JSON file in the `client/locales` directory with the format `xx.json`, where `xx` is the language code. For example, `fr.json` for French. You can use the existing language files as a reference.
2. Add the language code to the `availableLocales` value in the `client/config.js` file.
3. Import the new language file in the `client/stores/language/index.js` file.
4. Add the new language to the `localeContents` object in the `client/stores/language/index.js` file.
3. Add the translations for the new language to the JSON file you created. The JSON file should have the following structure:

```json
Expand Down
23 changes: 9 additions & 14 deletions client/stores/language/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import useGeneralStore from '@/stores/general';
import sleep from '@/lib/sleep';
import ReactPostprocessor from 'i18next-react-postprocessor';
import intervalPlural from 'i18next-intervalplural-postprocessor';
import en from '@/locales/en.json';
import tr from '@/locales/tr.json';
import az from '@/locales/az.json';

i18n
.use(new ReactPostprocessor())
Expand All @@ -17,17 +20,8 @@ i18n
postProcess: ['reactPostprocessor']
});

const localeContents = {};
let languageFirstlyChanged = false;

config.availableLocales
.map(async locale => {
const file = await import(`../../locales/${locale.code}.json`).catch(() => null);
if (!file) throw new Error(`Failed to load locale file for ${locale.code} at /locales/${locale.code}.json`);

localeContents[locale.code] = file.default;
});

const useLanguageStore = create(set => ({
language: 'loading',
setLanguage: async language => {
Expand Down Expand Up @@ -55,16 +49,17 @@ export function t(key, variables = {}) {

if (language === 'loading') return '';

if (!localeContents[language]) {
const defaultLanguage = config.availableLocales.find(locale => locale.default).code;
return localeContents[defaultLanguage]?.[key] || key;
}
const localeContents = {
en,
tr,
az
};

i18n.addResourceBundle(language, 'translation', localeContents[language], true, true);

if (!i18n.getResource(language, 'translation', key)) {
if (process.env.NODE_ENV === 'development') return `${key} (missing translation)`;
return localeContents[config.availableLocales.find(locale => locale.default).code][key] || key;
return key;
}

return i18n.t(key, {
Expand Down

0 comments on commit 5f1967c

Please sign in to comment.