ReferenceError:Node.js中未定义Intl

ReferenceError: Intl is not defined in Node.js

本文关键字:未定义 Intl js Node ReferenceError      更新时间:2023-09-26

我正试图在Node.js.中构造一个new Intl.Collator()对象

有人知道为什么Intl对象不会出现在Node运行时中吗?

根据MDN,它被ECMAScript指定为Namespace,所以我不明白为什么它不在那里。

不幸的是,除非您执行节点的自定义编译,否则节点当前(在撰写本文时为0.10版本)不支持ECMA-402 Intl对象,该编译记录在node.js Readme中。

支持libicu i18n:

svn checkout --force --revision 214189 '
   http://src.chromium.org/svn/trunk/deps/third_party/icu46 '
   deps/v8/third_party/icu46
./configure --with-icu-path=deps/v8/third_party/icu46/icu.gyp
make

制作安装

如果编译节点的自定义构建不是一种选择,或者这个想法让你感到恐惧,那么解决方法是使用intl模块,这是一个Javascript polyfill,它涵盖了EMCA-402标准的大部分内容,但Intl.Collator除外,其原因在项目Readme文件中有所说明。

使用模块是直接的:

npm install intl --save

然后在您的节点代码中:

var Intl = require('intl');
console.log(new Intl.NumberFormat("de-DE").format(12345678));

希望这能有所帮助。

由于io.js被合并到Node中,因此应该可以在Node的较新版本中使用Intl(从v3.1.0开始在io.js中提供)。

  • intl:使用小型icu的intl支持现在在构建中默认启用(Steven R.Loomis)#2264。
    • String#normalize()现在可以用于unicode规范化
    • Intl对象以及各种String和Number方法都存在,但仅支持英语区域设置
    • 为了支持所有区域设置,节点必须使用完整的icu构建

https://github.com/nodejs/node/blob/master/CHANGELOG.md#2015-08-18版本-310-fishrock 123

Node 0.12包含了对Intl的支持,但它只附带了ICU语言环境的一个子集(即:英语)。您需要使用完整ICU(或您需要的任何子集)的标志来构建Node。ICU构建的详细说明如下:https://github.com/nodejs/node/wiki/Intl

我建议阅读FormatJS文档:http://formatjs.io/

尤其是Intl Polyfill

https://github.com/andyearnshaw/Intl.js

var areIntlLocalesSupported = require('intl-locales-supported');
var localesMyAppSupports = [
    /* list locales here */
];
if (global.Intl) {
    // Determine if the built-in `Intl` has the locale data we need.
    if (!areIntlLocalesSupported(localesMyAppSupports)) {
        // `Intl` exists, but it doesn't have the data we need, so load the
        // polyfill and replace the constructors we need with the polyfill's.
        require('intl');
        Intl.NumberFormat   = IntlPolyfill.NumberFormat;
        Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
    }
} else {
    // No `Intl`, so use and load the polyfill.
    global.Intl = require('intl');
}

Intl.js没有(也永远不会)实现Intl.Collator。对于这个,你真的需要依赖使用所需语言环境构建的Node 0.12。