3

我正在尝试将 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

我希望那是:'Maio,2015'。

然后,如果我决定创建一个新变量,一切正常:

工作代码:

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 全局变量没有被替换?

4

2 回答 2

1

因为Intl全局对象的属性不可(在Node 0.12.2上测试):

console.log(Object.getOwnPropertyDescriptor(global, 'Intl'));
/*
{ value: {},
  writable: false,
  enumerable: false,
  configurable: false }
*/

将您的代码置于严格模式下,当尝试分配给不可写属性而不是静默失败时,它将引发更具描述性的错误。

它也是不可配置的,因此无法完全替换(重新分配)global.Intl. 这是一件好事:其他模块和依赖项可能依赖于内置Intl实现。

篡改全局范围通常会导致令人头疼的问题,最好让你的包保持独立。您可以只在需要的文件中要求 polyfill:

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

于 2015-05-21T23:02:52.610 回答
1

事实证明,仅替换 DateTimeFormat 和 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,以防您也在使用它。

我从这里得到了这个信息。

于 2015-05-22T20:02:36.530 回答