DEV Community

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

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman

No. A source code highlighter.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Didn't get it then. Can you explain it with detail and use-case? Thank you :)

Thread Thread
 
taufik_nurrohman profile image
Taufik Nurrohman • Edited

See this example that uses custom builder. Currently there is no way to load the language files dynamically. You still have to load them all at once even if you don’t need it.

I have made a plugin to overcome that, but never got into stable state. I still consider it buggy.

Thread Thread
 
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?