From 084752ac732a17f4b4c0ca701524d52d5fc6ec5d Mon Sep 17 00:00:00 2001 From: Gary Tsang Date: Thu, 7 Dec 2023 13:52:51 +0000 Subject: [PATCH 1/2] removed hardcoded language json imports for a more dynamic experience --- src/index.js | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/index.js b/src/index.js index 7d15c80..a881d7a 100644 --- a/src/index.js +++ b/src/index.js @@ -4,27 +4,20 @@ import Cookies from 'js-cookie'; import { createRoot } from 'react-dom/client'; import { BrowserRouter } from 'react-router-dom'; import { Provider } from 'react-redux'; -import messagesEN from './translations/en.json'; -import messagesTH from './translations/th.json'; -import messagesNL from './translations/nl.json'; - import App from './containers/App'; import * as serviceWorker from './serviceWorker'; import store from './redux/store'; const domNode = document.getElementById('root'); const root = createRoot(domNode); - -const messages = { - en: messagesEN, - nl: messagesNL, - th: messagesTH, -}; let language = navigator.language.split(/[-_]/)[0]; const cookieLanguage = Cookies.get('language'); if (cookieLanguage) { language = cookieLanguage; } +const messages = {}; +messages.en = await import('./translations/en.json'); +messages[language] = await import(`./translations/${language}.json`); language = language in messages ? language : 'en'; Cookies.set('language', language); From fcc1bb40fd4c336e22efc7d408d48e9d86412405 Mon Sep 17 00:00:00 2001 From: Gary Tsang Date: Thu, 7 Dec 2023 18:03:09 +0000 Subject: [PATCH 2/2] Using dynamic import instead --- src/index.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/index.js b/src/index.js index a881d7a..1c60a19 100644 --- a/src/index.js +++ b/src/index.js @@ -15,10 +15,19 @@ const cookieLanguage = Cookies.get('language'); if (cookieLanguage) { language = cookieLanguage; } -const messages = {}; -messages.en = await import('./translations/en.json'); -messages[language] = await import(`./translations/${language}.json`); -language = language in messages ? language : 'en'; +const messages = await (async () => { + const msgs = {}; + await import(`./translations/${language}.json`) + .catch(() => { + language = 'en'; + return import('./translations/en.json'); + }) + .then((fileContent) => { + msgs[language] = { ...fileContent }; + }); + return msgs; +})(); + Cookies.set('language', language); const theme = Cookies.get('theme');