[英]ReferenceError: Intl is not defined in Node.js
不幸的是,節點當前(從版本0.10開始,在編寫時)不支持ECMA-402 Intl
對象,除非您執行node.js 自述文件中記錄的節點的自定義編譯。
有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
make install
如果編譯節點的自定義構建不是一個選項或者這個想法充滿了恐懼,解決方法是使用intl模塊 ,一個Javascript polyfill,涵蓋了大部分的EMCA-402標准,除了Intl.Collator
,原因其中包含在項目自述文件中。
使用該模塊是直截了當的:
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:現在默認情況下在build(Steven R. Loomis) #2264中啟用使用small-icu的Intl支持。
- String#normalize()現在可用於unicode規范化。
- Intl對象和各種String和Number方法存在,但僅支持英語區域設置。
- 要支持所有語言環境,必須使用full-icu構建節點。
https://github.com/nodejs/node/blob/master/CHANGELOG.md#2015-08-18-version-310-fishrock123
節點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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.