Search code examples
javascriptnode.jsecmascript-intl

Node: Cannot replace Intl to use IntlPolyfill


I'm trying to use Intl with pt-BR locale and I can't get that to work with Node 0.12.

Code:

global.Intl = require('intl/Intl');
require('intl/locale-data/jsonp/pt-BR.js');

var options = { year: 'numeric', month: 'long' };
var dateTimeFormat = new Intl.DateTimeFormat('pt-BR', options);
console.log(dateTimeFormat.format(new Date()));

This code outputs:

May, 2015

I would expect that to be: 'Maio, 2015'.

Then, if I decide to create a new variable, everything works:

Working Code:

global.NewIntl = require('intl/Intl');
require('intl/locale-data/jsonp/pt-BR.js');

var options = { year: 'numeric', month: 'long' };
var dateTimeFormat = new NewIntl.DateTimeFormat('pt-BR', options);
console.log(dateTimeFormat.format(new Date()));

This prints out the expect value. Question: Why the Intl global variable is not being replaced?


Solution

  • It turns out that replacing only DateTimeFormat and NumberFormat solves the issue:

    require('intl/Intl');
    require('intl/locale-data/jsonp/pt-BR.js');
    Intl.NumberFormat = IntlPolyfill.NumberFormat;
    Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
    
    var options = { year: 'numeric', month: 'long' };
    var dateTimeFormat = new Intl.DateTimeFormat('pt-BR', options);
    console.log(dateTimeFormat.format(new Date()));
    

    Just make sure to load this script before loading react-intl in case you are also using it.

    I got this information from here.