intl(内置国际化)

2024-06-27 10:01:11 383
intl是 JavaScript 的内置国际化 API,简称 ECMAScript Internationalization API(ECMA-402)。它为格式化数字、日期、时间和字符串提供了标准化的国际化支持,是现代 Web 应用程序中处理多语言和区域化内容的基础工具。

特点

  1. 标准化支持:基于 ECMAScript 标准,保证了跨浏览器和跨平台的一致性。
  2. 多语言支持:支持多种语言和区域,能够处理不同文化背景下的日期、时间、数字和货币格式化。
  3. 丰富的格式化选项:提供多种格式化选项,满足复杂的国际化需求。
  4. 高性能:作为内置 API,性能优于外部库。
  5. 可扩展性:通过 polyfills 扩展对旧浏览器的支持。

使用场景

  1. 国际化网站和应用:需要支持多语言显示的项目。
  2. 跨平台应用:确保在不同浏览器和操作系统上一致的用户体验。
  3. 财务应用:需要精确处理和显示货币格式。
  4. 日历和时间表:根据用户的本地时间格式显示日期和时间。

安装方式

intl API 是 ECMAScript 的一部分,现代浏览器和 Node.js 环境中已经内置,无需安装。但对于旧版环境,可以通过 polyfill 添加支持。

安装 polyfill

npm install intl

使用示例

格式化日期和时间

const date = new Date(Date.UTC(2024, 5, 26, 19, 0, 0));

// 英文格式
console.log(new Intl.DateTimeFormat('en-US').format(date));
// 输出: 6/26/2024

// 中文格式
console.log(new Intl.DateTimeFormat('zh-CN').format(date));
// 输出: 2024/6/26

格式化数字

const number = 123456.789;

// 英文格式
console.log(new Intl.NumberFormat('en-US').format(number));
// 输出: 123,456.789

// 中文格式
console.log(new Intl.NumberFormat('zh-CN').format(number));
// 输出: 123,456.789

格式化货币

const price = 1000;

// 美元格式
console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(price));
// 输出: $1,000.00

// 欧元格式
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(price));
// 输出: 1.000,00 €

常用 API 介绍

  1. Intl.DateTimeFormat:格式化日期和时间。

    • new Intl.DateTimeFormat(locale, options):创建格式化对象。
    • format(date):格式化日期。
  2. Intl.NumberFormat:格式化数字。

    • new Intl.NumberFormat(locale, options):创建格式化对象。
    • format(number):格式化数字。
  3. Intl.Collator:字符串比较。

    • new Intl.Collator(locale, options):创建比较对象。
    • compare(string1, string2):比较两个字符串。
  4. Intl.RelativeTimeFormat:格式化相对时间。

    • new Intl.RelativeTimeFormat(locale, options):创建格式化对象。
    • format(value, unit):格式化相对时间。
  5. Intl.PluralRules:确定复数形式。

    • new Intl.PluralRules(locale, options):创建规则对象。
    • select(number):确定复数形式。

高级用法

使用 polyfill 添加对旧浏览器的支持

import 'intl';
import 'intl/locale-data/jsonp/en';
import 'intl/locale-data/jsonp/zh';

// 然后可以像现代浏览器一样使用 Intl API
const date = new Date(Date.UTC(2024, 5, 26, 19, 0, 0));
console.log(new Intl.DateTimeFormat('en-US').format(date));

自定义区域数据 可以通过自定义区域数据来扩展 Intl 的功能:

const customData = {
  data: {
    en: {
      units: {
        temperature: {
          short: {
            Celsius: { symbol: '℃', style: 'unit', unitDisplay: 'short' },
          },
        },
      },
    },
  },
};

// 使用 customData 自定义区域数据
const formatter = new Intl.NumberFormat('en', customData);
console.log(formatter.format(25)); // 输出: 25℃

官方资料