Last active
March 13, 2021 21:41
-
-
Save sesam/c978f77c3ccf5629f5a753ef299b82a2 to your computer and use it in GitHub Desktop.
PATCH: Enable webpack code splitting and load translations on demand
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+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