Intl.NumberFormat 在节点和浏览器中的不同行为
Different behaviour of Intl.NumberFormat in node and browser
如果我在浏览器和节点中 运行 这段代码,我会得到两个不同的结果:
const moneyFormatter = new Intl.NumberFormat('it-IT', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2
});
moneyFormatter.format(1);
浏览器:1,00 €
节点:€1.00
ICU 和节点
此问题是由于默认节点构建中缺少 ICU 数据引起的。
Nodejs docs explain it这个功能不错:
Node.js (and its underlying V8 engine) uses ICU to implement these features in native C/C++ code. However, some of them require a very large ICU data file in order to support all locales of the world.
及其在默认节点构建中的限制:
Because it is expected that most Node.js users will make use of only a small portion of ICU functionality, only a subset of the full ICU data set is provided by Node.js by default.
所以:
Several options are provided for customizing and expanding the ICU data set either when building or running Node.js.
快速解决
安装 full-icu
npm 包,大功告成:每个语言环境都将被安装并可以使用。只需使用指向 icu 数据集安装的专用环境变量启动您的应用程序:
NODE_ICU_DATA=node_modules/full-icu node YOURAPP.js
或者,使用替代节点选项:
node --icu-data-dir=node_modules/full-icu YOURAPP.js
此解决方案的唯一缺点是完整 icu 数据集所需的 space:~27Mb。
慢,但 space 优化的解决方案
从源代码编译节点 bundling it with only a specific ICU。
正在检查可用的语言环境
Intl.NumberFormat.supportedLocalesOf('it')
它 returns 一个空数组 []
如果不支持语言环境。
它 returns 一个具有区域设置 ID ['it']
的数组,如果该区域设置受支持的话。
如果我在浏览器和节点中 运行 这段代码,我会得到两个不同的结果:
const moneyFormatter = new Intl.NumberFormat('it-IT', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2
});
moneyFormatter.format(1);
浏览器:1,00 €
节点:€1.00
ICU 和节点
此问题是由于默认节点构建中缺少 ICU 数据引起的。
Nodejs docs explain it这个功能不错:
Node.js (and its underlying V8 engine) uses ICU to implement these features in native C/C++ code. However, some of them require a very large ICU data file in order to support all locales of the world.
及其在默认节点构建中的限制:
Because it is expected that most Node.js users will make use of only a small portion of ICU functionality, only a subset of the full ICU data set is provided by Node.js by default.
所以:
Several options are provided for customizing and expanding the ICU data set either when building or running Node.js.
快速解决
安装 full-icu
npm 包,大功告成:每个语言环境都将被安装并可以使用。只需使用指向 icu 数据集安装的专用环境变量启动您的应用程序:
NODE_ICU_DATA=node_modules/full-icu node YOURAPP.js
或者,使用替代节点选项:
node --icu-data-dir=node_modules/full-icu YOURAPP.js
此解决方案的唯一缺点是完整 icu 数据集所需的 space:~27Mb。
慢,但 space 优化的解决方案
从源代码编译节点 bundling it with only a specific ICU。
正在检查可用的语言环境
Intl.NumberFormat.supportedLocalesOf('it')
它 returns 一个空数组 []
如果不支持语言环境。
它 returns 一个具有区域设置 ID ['it']
的数组,如果该区域设置受支持的话。