节点:无法replaceIntl以使用IntlPolyfill
我正在尝试使用Intl与pt-BR语言环境,并且我无法使用Node 0.12。
码:
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()));
这个代码输出:
May, 2015
我希望是:“2015年的Maio”。
然后,如果我决定创build一个新的variables,一切工作:
工作代码:
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()));
这打印出期望值。 问题 :为什么Intl全局variables不被replace?
由于全局对象的Intl
属性不可写 (在节点0.12.2上testing):
console.log(Object.getOwnPropertyDescriptor(global, 'Intl')); /* { value: {}, writable: false, enumerable: false, configurable: false } */
把你的代码放在严格模式下 ,当试图分配给不可写属性而不是静默失败时,会抛出更多的描述性错误。
这也是不可configuration的,所以没有办法完全替代(重新分配) global.Intl
。 这是一件好事:其他模块和依赖可能取决于内置的Intl
实现。
篡改全球范围往往会导致更多的头痛,这是最好的保持你的包装独立。 您可以在需要的文件中只需要填充:
var Intl = require('intl/Intl'); // Note: you only need to require the locale once 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()));
你可以添加var Intl = require('intl/Intl');
在你需要Intl
的文件中。
事实certificate,只replaceDateTimeFormat和NumberFormat解决了这个问题:
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()));
只要确保在加载react-intl
之前加载这个脚本,以防你也在使用它。
我从这里得到这个信息。