moment / moment

Parse, validate, manipulate, and display dates in javascript.
momentjs.com
MIT License
47.99k stars 7.04k forks source link

How to dynamically load moment locales with react in a SPA and force a re-render in local env and production? #5929

Open gazpachu opened 3 years ago

gazpachu commented 3 years ago

I'm reposting my question here for people looking for the same answer in the future:

https://stackoverflow.com/questions/69051040/how-to-dynamically-load-moment-locales-with-react-in-a-spa-and-force-a-re-render

I resist the idea of loading the moment locales all at once (in my case 18, 70+KB) and I was wondering what would be the best approach to load them dynamically.

This is what I've got so far, but it has a few caveats:

const [, { languages }] = useTranslation();

useEffect(() => {
  async function loadMomentLocale() {
    // Requires a switch because dynamic imports don't support string interpolation
    switch (languages[0]) {
      case 'es':
        await import('moment/locale/es');
        break;
      case 'fr':
        await import('moment/locale/fr');
        break;
    }
  }

  if (languages) {
    loadMomentLocale().then(() => moment.locale(languages[0]));
  }
}, [languages]);
Eesssn commented 6 months ago

is there any update?

fillobotto commented 1 week ago

is there any update?

If you are using i18next for localization, then drop moment and use integrated formatting feature as described here:

https://www.i18next.com/translation-function/formatting