跳转至主要内容
JavaScript i18n

JavaScript 国际化:利用 Intl API 实现浏览器原生国际化

JavaScript 将 Intl API 作为内置标准,用于格式化数字、日期和列表,以及处理不同语言环境下的复数规则。无需外部库。该 API 受到所有现代浏览器和 Node.js 的支持,开箱即用即可提供基于语言环境的字符串比较、分段和相对时间格式化功能。

Package
lefine/strings
Runs in
Browsers · Node · Deno · Bun · Workers
lefine
01终端
npm install lefine
02i18n.js
import { createTranslator } from 'lefine/strings'import messages from './locales/en.json' with { type: 'json' }// messages is { namespace: { key: text } }, as pull wrote itexport const t = createTranslator({  locale: 'en',  messages,  namespace: 'home',})
03main.js
import { t } from './i18n.js'document.querySelector('h1').textContent = t('title')// ICU values work too: "Hello, {name}"document.querySelector('p').textContent = t('greeting', { name: 'World' })
t('title')
Welcome
01/Setup

用三步将 i18n 添加到纯 JavaScript 中

无需安装专门针对 JavaScript 的包:@better-i18n/core 是所有其他 SDK 的纯 JavaScript 客户端核心。

  1. 01

    安装客户端

    一个无依赖包。它可在浏览器、Node、Deno、Bun 和 Cloudflare Workers 中运行。

    terminalbash
    npm install lefinenpx lefine loginnpx lefine strings pull -o locales# lefine/strings has no framework dependency.# pull writes locales/en.json, de.json, ...
  2. 02

    创建客户端一次

    在模块作用域中实例化,并在需要的地方导入:一个客户端、一份配置,所有调用共享同一个内存缓存。

    i18n.js
    import { createTranslator } from 'lefine/strings'import messages from './locales/en.json' with { type: 'json' }// messages is { namespace: { key: text } }, as pull wrote itexport const t = createTranslator({  locale: 'en',  messages,  namespace: 'home',})
  3. 03

    Read a message

    getMessages 返回一个普通的嵌套对象,所以四行的查找辅助函数就是你所需的全部运行时。

    main.js
    import { t } from './i18n.js'document.querySelector('h1').textContent = t('title')// ICU values work too: "Hello, {name}"document.querySelector('p').textContent = t('greeting', { name: 'World' })
02/Two ways

使用客户端或 fetch

客户端增加了缓存、重试和回退链。如果你想自行管理,这个 CDN 是一个纯 JSON 端点。

locale.js
import { createTranslator } from 'lefine/strings'let t = createTranslator({ locale: 'en', messages: await load('en'), namespace: 'home' })async function load(locale) {  const res = await fetch(`/locales/${locale}.json`) // the files pull wrote  return res.json()}export async function setLocale(next) {  t = createTranslator({ locale: next, messages: await load(next), namespace: 'home' })  document.documentElement.lang = next  render()}
03/Formatting

JavaScript Intl API 实践

在任意现代浏览器或 Node.js 运行时中,使用内置 Intl 构造函数对货币、日期和序数进行格式化,输出符合区域设置的内容。

format.js
// Using the built-in Intl APIconst formatter = new Intl.NumberFormat('de-DE', {  style: 'currency',  currency: 'EUR',});console.log(formatter.format(1234.56)); // "1.234,56 €"// Date formattingconst date = new Intl.DateTimeFormat('ja-JP', {  year: 'numeric',  month: 'long',  day: 'numeric',});console.log(date.format(new Date())); // "2026年3月2日"// Pluralizationconst plural = new Intl.PluralRules('en');const suffixes = { one: 'st', two: 'nd', few: 'rd', other: 'th' };function ordinal(n) {  return `${n}${suffixes[plural.select(n)]}`;}
04/Capabilities

JavaScript Intl API 功能

  • 内置的 Intl API,无需外部依赖即可完成核心国际化操作
  • Intl.NumberFormat,用于感知区域设置的货币、百分比和单位格式化
  • Intl.DateTimeFormat:用于特定区域设置的日期和时间显示格式
  • 适用于100多个地区序数词和基数词复数形式的国际复数规则
  • ICU MessageFormat:通过 intl-messageformat 等库支持复数形式、选择项和嵌套结构(Intl 未内置)
  • Intl.RelativeTimeFormat,用于生成人类可读的相对日期(例如“3 天前”)
  • Intl.ListFormat:用于支持区域设置的联结与析取列表
  • Intl.Collator,用于区分语言的字符串排序和比较
  • 用于单词、句子和字母边界检测的国际分词器
How it works

JavaScript 字符串的来源

无构建步骤且无打包的语言文件:客户端在运行时解析语言,边缘节点响应请求。

Read path — every locale load
Your JavaScript app

Reads from the plain object the pulled JSON file already gave.

0 network calls per render

lefine

getMessages(locale) — served from the in-memory cache if it is warm.

60 s cache · 0 deps

CDN edge

Cloudflare worker answers from the nearest edge cache.

max-age=60 · never a 5xx

R2 object store

The published translation files the sync worker wrote.

source of truth

Fallback chain — tried in order when a hop fails
  • 01In-memory TTL cache
  • 02CDN fetch, with timeout and one retry
  • 03Persistent storage, if configured
  • 04staticData bundled with the app
  • 05Throw — after everything above missed
Write path — dashboard to app
AI or translator

Proposal reviewed in the dashboard, glossary enforced.

MCP · dashboard · CLI

Publish

Sync worker writes the locale files to R2.

lefine strings publish

CDN purge

Fire-and-forget purge of the affected keys and the manifest.

non-critical by design

Live in the app

The next getMessages() past the TTL returns the new copy.

~5 min worst case

0dependencies in core
5 minSDK cache in production; edge 60s
200CDN status, even on failure
5fallback layers before an error
Get started

免费开始。

立即开始 JavaScript 国际化

借助人工智能驱动的工作流、命令行同步以及边缘 CDN 交付,管理您的 JavaScript 翻译。