adamwdraper / Numeral-js

A javascript library for formatting and manipulating numbers.
http://numeraljs.com
MIT License
9.67k stars 930 forks source link

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

Open ephemer opened 10 years ago

ephemer commented 10 years ago

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 commented 10 years ago
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?

feliperoberto commented 9 years ago

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);
}
Noitidart commented 3 years ago

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')