Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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