DEV Community

Discussion on: Share your ideas that never made it to production

 
joelbonetr profile image
JoelBonetR 🥇 • Edited

You don't need to load them all.
Just use dynamic imports...

const translation = (locale) => import(`/translations/lang-${locale}.js`);
Enter fullscreen mode Exit fullscreen mode

or async:

const loadTranslations = async (locale) => await import(`/translations/lang-${locale}.js`);
Enter fullscreen mode Exit fullscreen mode

Another (more robust) example:

/**
 * Retrieves translations from a given locale
 * @param {string} locale
 * @returns {Object}
 */
const getTranslations = (locale) => {
  try {
    const availableLanguages = {
      en: dynamic(() => import('/translations/en.js')),
      es: dynamic(() => import('/translations/es.js')),
    };

    if (!availableLanguages.hasOwnProperty(locale)) {
      console.error(`getTranslations error. Could not load translations for ${locale}`);
      return availableLanguages['en']; // DEFAULT
    }
    return availableLanguages[locale];
  } catch (error) {
    console.error(`${error.message} in ${error.stack}`);
  }
};
Enter fullscreen mode Exit fullscreen mode

Here we are declaring the available langs so it will not fail in runtime trying to load a nonexistent file for any other error, and it will return the default language in case of such error.

You can use next/dynamic if working with Next JS like me in this last example (note that there's no dynamic function declared; if you are not using Next JS, it needs to be done but you can use the first or second example to create a dynamic implementation quickly).
i.e.

const dynamic = (path) => import(`${path}`);
Enter fullscreen mode Exit fullscreen mode

Here you can find a dynamic import explanation from javascript.info

Apart from those options, in most webapps is better to handle translations through the DB so you can build a dashboard and people that work as translators can do their thing on it instead. No more releases to fix a string 😄

Best regards

Thread Thread
 
benhatsor profile image
Ben Hatsor

A plugin like this one?

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Why do you want a plugin when it's so easy to handle with vanilla JS?