Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically require momentjs locale

Hi Im using expressjs for a backend service in which in need to set the locale for momentjs based on the user browser locale. Im looking for any strategies on how to load the moment/locale/{locale-file based} based on expressjs request.acceptsLanguages.

Any help is greatly appreciated

like image 831
jlarding Avatar asked Jan 31 '17 16:01

jlarding


People also ask

How do I change locale globally moments?

You can change moment locale globally like that: import moment from 'moment'; import localization from 'moment/locale/fr'; moment. locale('fr', localization); I hope this helps you.

How do I import a locale moment?

moment. Loading locales in NodeJS is super easy. If there is a locale file in moment/locale/ named after that key, import it first, then call moment. locale to load it. To save the step of loading individual locales (i.e. just load them all), import the moment/min/moment-with-locales module instead.

Why is MomentJS so big?

Since the Moment. js package isn't modularized and, per the threads on Github issues, it won't be done as support is ending and they have termed it a legacy project. This is the primary reason behind those large chunks in the build size.


1 Answers

You can just use a .locale() function after parsing correct language from request (but you have send a language header at least)

const moment = require('moment');
const language = getLanguageFromRequest(req); // or whatever logic you like
moment.locale(language);

but maybe it is better idea to handle it in browser, not in a backend.

like image 148
l2ysho Avatar answered Oct 14 '22 22:10

l2ysho