Skip to content

Instantly share code, notes, and snippets.

@SimeonC
Last active May 15, 2024 02:04
Show Gist options
  • Save SimeonC/6a738467c691eef7f21ebf96918cd95f to your computer and use it in GitHub Desktop.
Save SimeonC/6a738467c691eef7f21ebf96918cd95f to your computer and use it in GitHub Desktop.
Using Webpack code-split "backend" for i18next translations. Note that your withTranslations/useTranslations must use namespaces or include a default namespace or the read function doesn't get called
// Used for one JSON file for each language containing all namespaces
i18next.use({
type: 'backend',
read<Namespace extends keyof typeof en>(
language: LocaleCode,
namespace: Namespace,
callback: (
errorValue: unknown,
translations: null | typeof en[Namespace]
) => void
) {
import(`./locales/${language}.json`)
.then((resources) => {
callback(null, resources[namespace]);
})
.catch((error) => {
callback(error, null);
});
}
});
// Used for each JSON file is contains a single namespace for the language
i18next.use({
type: 'backend',
read<Namespace extends keyof typeof en>(
language: LocaleCode,
namespace: Namespace,
callback: (
errorValue: unknown,
translations: null | typeof en[Namespace]
) => void
) {
import(`./locales/${language}/${namespace}.json`)
.then((resources) => {
callback(null, resources);
})
.catch((error) => {
callback(error, null);
});
}
});
// Used for not namespacing, ie `defaultNamespace: 'translations'`
i18next.use({
type: 'backend',
read<Namespace extends keyof typeof en>(
language: LocaleCode,
namespace: Namespace,
callback: (
errorValue: unknown,
translations: null | typeof en[Namespace]
) => void
) {
import(`./locales/${language}.json`)
.then((resources) => {
callback(null, resources);
})
.catch((error) => {
callback(error, null);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment