Skip to content

Instantly share code, notes, and snippets.

@sesam
Last active March 13, 2021 21:41
Show Gist options
  • Save sesam/c978f77c3ccf5629f5a753ef299b82a2 to your computer and use it in GitHub Desktop.
Save sesam/c978f77c3ccf5629f5a753ef299b82a2 to your computer and use it in GitHub Desktop.
PATCH: Enable webpack code splitting and load translations on demand
+export default function SuspendableLanguageSetter() {
+ return (
+ <React.Suspense fallback={""}>
+ <LanguageSetter />
+ </React.Suspense>
+ );
+}
-const translations = () => ({
- "en-GB": require("./en-GB/translations.json"),
- "en-US": require("./en-US/translations.json"),
- "sv-SE": require("./sv-SE/translations.json"),
-});
+const lazyTranslations = {
+ "en-US": () => import("./en-US/translations.json"),
+ "sv-SE": () => import("./sv-SE/translations.json"),
+};
+const en_GB = require("./en-GB/translations.json");
+class WebpackyBackend {
+ read(language, namespace, callback) {
+ const loader = lazyTranslations[language];
+ if (!loader) return callback(null, true); // language missing
+ loader()
+ .then((res) => callback(null, res.default.translations))
+ .catch((err) => callback(err, false));
+ }
+}
+WebpackyBackend.type = "backend";
+
+const resources = {
+ "en-GB": en_GB,
+};
+
+i18n
+ .use(initReactI18next)
+ .use(WebpackyBackend)
+ .init({
+ resources,
+ lng: "en-GB",
+ fallbackLng: "en-GB",
+ load: "currentOnly", // avoids loading "en" right after loading "en-GB"
+ ns: ["translations"],
+ defaultNS: "translations",
+
+ partialBundledLanguages: true, // this allows loading translations on demand via WebpackyBackend
+ // NOTE: supposedly react.wait = true should be used here. But I see no difference in app useage / reload behavior, so not adding that for now.
+
+ keySeparator: false, // we use content as keys
+ interpolation: { escapeValue: false },
+ });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment