Search code examples
javascriptasp.netjsonreactjsecmascript-intl

Formatting Number and dates dilemma


My app is using :

  • ASP.NET Http Handler for the back-end in order to read the data from MySql database and return them in JSON format
  • React.js app for the front-end to display the data in the browsers. The app is built by using webpack.

Several pages of the app display Dates and Numbers and I would like to format them according to the browser's preferred language. I found that the cutting edge for this feature is ECMAScript Internationalization API and its polyfill Intl.js : https://github.com/andyearnshaw/Intl.js. I added it in my app's dependencies and used for formatting, for example:

'use strict';

var React = require('react');

var Intl = require('intl');

var formatter = new Intl.DateTimeFormat();

module.exports = React.createClass({
    render : function(){
        if(this.props.value) {
            var formattedValue = formatter.format(new Date(this.props.value));
            return (
                <span>
                    {formattedValue}
                </span>
            );
        }
        else{
            return false;
        }
    }
});

So far so good, but then I found that the size of the minified bundle.js increases significantly after adding Intl.js in dependencies : 300Kb raised to 900kb! I understand that it happens because locale-data folder(https://github.com/andyearnshaw/Intl.js/tree/master/locale-data) is automatically added at runtime and it is really needed, but I still can't accept that fact that the size of app's script raised 3 times just because it needs to display formatted dates and numbers... So, I am thinking about delegating the formatting to the server side so that it returns Dates and Numbers as formatted strings within the Json response. That's quite easy to implement and I can see a couple of perks of this approach:

  • Preserving the small size of app
  • Possible performance improvements

but I don't see any obvious shortcomings and that's suspicious. So, my question is - what are the disadvantages of formatting dates and numbers on server side and sending them as formatted strings within the Json response?


Solution

  • The problem is that you require a round trip to the server for formatting, which really is a view concern and not a server concern (unless you're rendering on the server, which you don't seem to be doing).

    Instead of bundling in all locales (even the ones irrelevant to the user) is what makes your bundle grow. You shouldn't include all of them into the bundle, but instead separate that into a separate bundle. You can either look at the Accept-Language HTTP header on the server and serve up the correct language, or use Javascript to check the locale and make a request for that specific language.