Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MomentJs: Having to import each moment locale for all possible languages?

After having some problems getting momentjs localized date formats to work properly, I happened upon a thread that correctly stated that the target moment locale resource would have to be imported, e.g., for French (fr):

import 'moment/locale/fr';

and indeed this works. However this would would imply that the module I'm coding using moment would have to explicitly import every moment locale module? If so, this implies that the code would have to be touched every time a new locale is supported? This would't seem right.

I'm hoping for a better solution for this.

like image 289
Maniaque Avatar asked Sep 28 '18 15:09

Maniaque


People also ask

How to create language specific instance of moment?

In the docs, you can create language specific instances of moment by doing that. If you format first, the language won't process. Alternatively, you could do something like var deMoment = moment (); deMoment.lang ('de') and reuse deMoment instead of moment throughout your script. update: Deprecation warning: moment ().lang () is deprecated.

Why should you use moment JS for localization?

One of the reasons is also the way in which localization is handled in Moment.js. That too is with minimal code implementations. For achieving localization using Moment.js, moment-with-locales.min.js is used.

How to display the current country in momentjs?

You'd need to add moment.lang (navigator.language) in your script. And must also add each country locale you want to display in : for example for GB or FR, you need to add that locale format in moment.js library. An example of such format is available in momentjs documentation.

Can we create moment objects with a specific locale?

This means that, if there is a way to create moment object with a specific locale, changing the locale globally should affect all already existing objects, that do not have definite locale. At least there should be a way to do this even if not by default for some backward compatibility.


1 Answers

Usually the list of supported application languages is limited, so it's unreasonable to load all available Moment locales because of increased footprint.

Moment package contains prebundled locales for this purpose. E.g:

import moment from 'moment';
import 'moment/min/locales';

Or:

import moment from 'moment/min/moment-with-locales';
like image 92
Estus Flask Avatar answered Nov 15 '22 23:11

Estus Flask