Numeral-js icon indicating copy to clipboard operation
Numeral-js copied to clipboard

question: how to dynamically (or otherwise) load languages in node?

Open ephemer opened this issue 10 years ago • 3 comments

Hello, I'm trying to dynamically switch locales in my node app (via numeral.language(locale); ). Have spent the last hour trying to figure out why I keep getting the following error when switching the locale to German / any other language:

Error: Unknown language : de

German ('de') is clearly one of the included languages. I guess that means the languages.js file isn't loaded automatically in node. It looks like the languages aren't even defined by name (for node's module.exports) in languages.js - I'm fairly confused by it all. Why would there be a languages.js file containing every language if those languages can't be loaded dynamically?

Can anyone explain what I'm doing wrong / whether what I'm trying is possible? I'm hoping not to have to manually copy/paste the contents of the locale files into the main numeral.js file...

ephemer avatar Jan 08 '14 18:01 ephemer

var supportedLngs = ['en', 'de'];

_.each(supportedLngs, function (lng) {
  if( lng === 'en' ) return;
  var obj = require('numeral/languages/'+lng);
  numeral.language(lng, obj);
});

ok I looked at some more questions on here and came up with this solution (requires lodash / underscore). maybe there's a better one?

ephemer avatar Jan 08 '14 18:01 ephemer

without lodash:

var supportedLngs = ['pt-br'];

supportedLngs.forEach(function(lng){
  if( lng === 'en' ) return;
  var obj = require('numeral/languages/'+lng);
  numeral.language(lng, obj);
});

or

var supportedLngs = ['pt-br'];

for(var i=0;i<supportedLngs.length;i++){
    if( supportedLngs[i] === 'en' ) return;
    var obj = require('numeral/languages/'+supportedLngs[i]);
    numeral.language(supportedLngs[i], obj);
}

feliperoberto avatar Mar 21 '15 22:03 feliperoberto

Thanks for sharing this, I actually can't figure out how to load the locale either. Simply doing numeral.locale('en-gb') causes a crash. I'm using react native. The error I get is:

TypeError, undefined is not an object (evaluating 'locale.delimiters')

Noitidart avatar Jun 06 '21 01:06 Noitidart