Search code examples
javascriptecmascript-6aureliaes6-module-loadernumeral.js

import all languages for numeral.js in es2016 for an Aurelia app


I want to use a CurrencyValueConverter like the one in the aurelia.io documentation, but localizing the result to Dutch or German, but I don't know how to make all languages available to numeral.

I am able to import the Ducth locale en load it explicitly as follows:

import numeral from 'numeral';
import nl from "numeral/languages/nl-nl";

export class CurrencyValueConverter {
  toView(value, language = "nl-nl") {
    numeral.language(language, nl); // this line loads the nl language definition
    numeral.language(language);
    return numeral(value).format("$0,0.00");
  }
}

But of course, this only works for one language. How can I load multiple languages while avoiding something like

if(language === "nl-nl")
    numeral.language(language, nl);
else if(language === "de-de")
    // etc

Solution

  • Here's an example: https://gist.run?id=6af6cf41d4f8dc206aaa

    app.html

    <template>
      <require from="./currency-value-converter"></require>
    
      <label>
        Language:
        <select value.bind="selectedLanguage">
          <option repeat.for="language of languages" value.bind="language">${language}</option>
        </select>
      </label>
    
      <h1>${value | currency:selectedLanguage}</h1>
    </template>
    

    app.js

    export class App {
      value = 1234567.890123;
      selectedLanguage = 'nl-nl';
      languages = [
        'en-gb',
        'es',
        'et',
        'fi',
        'fr',
        'fr-CA',
        'fr-ch',
        'hu',
        'it',
        'ja',
        'nl-nl',
        'pl',
        'pt-br',
        'pt-pt',
        'ru',
        'ru-UA',
        'sk',
        'th',
        'tr',
        'uk-UA',
        'be-nl',
        'chs',
        'cs',
        'da-dk',
        'de',
        'de-ch'];
    }
    

    currency-value-converter.js

    import numeral from 'numeral';
    import 'numeral/min/languages.min';
    
    export class CurrencyValueConverter {
      toView(value, language = 'nl-nl') {
        numeral.language(language);
        return numeral(value).format('$0,0.00');
      }
    }