@embra/i18n

中文文档
0.1.0发布于 2026/07/23MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1.1万

A lightweight, reactive internationalization library.

原始使用文档
文档目录17 节
  1. Install
  2. Features
  3. Usage
  4. Detect Language
  5. Message Formatting
  6. Pluralization
  7. Modifier Matching
  8. Reactive I18n
  9. Namespace
  10. Hot Module Replacement
  11. Dynamic Import
  12. React
  13. Cascading I18nProvider
  14. Trans Component
  15. Astro
  16. VSCode Extension
  17. For AI Coding Agents

@embra/i18n

Docs Build Status npm-version Coverage Status

A lightweight, reactive internationalization library.

export size

Install

npm add @embra/reactivity @embra/i18n

Features

  • Subscribable reactive lang$, t$ and locales$.
  • Lightweight and fast t() translation.
  • Nested locale messages.
  • Message formatting and pluralization.
  • Easy dynamic locale loading.
  • Locale namespaces.
  • First-class React support.

Usage

Create an I18n instance with static locales:

import { I18n, type Locales } from "@embra/i18n";

const locales: Locales = {
  en: {
    stock: {
      fruit: "apple",
    },
  },
};

const i18n = new I18n("en", locales);
i18n.t("stock.fruit"); // apple

// add more locales later
const zhCN = await import(`./locales/zh-CN.json`);
i18n.addLocale("zh-CN", zhCN);

// or replace all locales manually
const zhTW = await import(`./locales/zh-TW.json`);
i18n.locales$.set({ "zh-TW": zhTW });

You can also create an I18n instance with preloaded dynamic locales:

import { I18n } from "@embra/i18n";

const i18n = await I18n.preload("en", lang => import(`./locales/${lang}.json`));
// Locale `./locales/en.json` is preloaded

await i18n.switchLang("zh-CN"); // Locale `./locales/zh-CN.json` is loaded

Detect Language

You can detect language of browser/nodejs via detectLang. BCP 47 tags and sub-tags are supported.

import { detectLang } from "@embra/i18n";

detectLang(); // "en-US"

const i18n = await I18n.preload(
  // language sub-tag is matched
  detectLang(["en", "zh-CN"]) || "zh-TW", // "en"
  lang => import(`./locales/${lang}.json`),
);

Message Formatting

Message keys are surrounded by double curly brackets:

import { I18n, type Locales } from "@embra/i18n";

const locales: Locales = {
  en: {
    stock: {
      fruit: "apple",
    },
    fav_fruit: "I love {{fruit}}",
  },
};

const i18n = new I18n("en", locales);
const fruit = i18n.t("stock.fruit"); // apple
i18n.t("fav_fruit", { fruit }); // I love apple

Placeholders without a corresponding value are preserved. This allows the remaining placeholders to be processed later, such as by the Trans component:

i18n.t("fav_fruit", {}); // I love {{fruit}}

It also works with array:

import { I18n, type Locales } from "@embra/i18n";

const locales: Locales = {
  en: {
    fav_fruit: "I love {{0}} and {{1}}",
  },
};

const i18n = new I18n("en", locales);
i18n.t("fav_fruit", ["apple", "banana"]); // I love apple and banana

Pluralization

You can easily do pluralization with Modifier Matching.

import { I18n, type Locales } from "@embra/i18n";

const locales: Locales = {
  en: {
    apple: "{{@}} apples", // fallback
    "apple@0": "No apple", // matching { "@": 0 } or { "@": "0" }
    "apple@1": "An apple", // matching { "@": 1 } or { "@": "1" }
  },
};

const i18n = new I18n("en", locales);
i18n.t("apples", { "@": 0 }); // No apple
i18n.t("apples", { "@": 1 }); // An apple
i18n.t("apples", { "@": 3 }); // 3 apples

Modifier Matching

You can use @ to match different modifiers.

For example:

i18n.t("a.b.c", { "@": "d" });

It will look for "a.b.c@d" and fallback to "a.b.c" if not found.

See Pluralization for more examples.

Reactive I18n

i18n.lang$, i18n.t$ and i18n.locales$ are subscribable values.

See @embra/reactivity for more details.

i18n.lang$.reaction(lang => {
  // logs lang on changed
  console.log(lang);
});

i18n.lang$.subscribe(lang => {
  // logs lang immediately and on changed
  console.log(lang);
});

Namespace

I18n instance is cheap to create. You can create multiple instances for different namespaces.

import { I18n } from "@embra/i18n";

// Module Login
async function moduleLogin() {
  const i18n = await I18n.preload("en", lang => import(`./locales/login/${lang}.json`));

  console.log(i18n.t("password"));
}

// Module About
async function moduleAbout() {
  const i18n = await I18n.preload("en", lang => import(`./locales/about/${lang}.json`));

  console.log(i18n.t("author"));
}

Hot Module Replacement

To use Vite HMR for locales:

const i18n = await I18n.preload("en", lang => import(`./locales/${lang}.json`));

if (import.meta.hot) {
  import.meta.hot.accept(["./locales/en.json", "./locales/zh-CN.json"], ([en, zhCN]) => {
    i18n.locales$.set({
      ...i18n.locales,
      en: en?.default || i18n.locales.en,
      "zh-CN": zhCN?.default || i18n.locales["zh-CN"],
    });
  });
}

Dynamic Import

Although you can simply use import() to dynamically load locales, with bundler API you can do more.

For example with Vite you can use glob import to statically get info of all locales. This way allows you to add or remove locales without changing source code.

import { I18n, detectLang, type Locale, type LocaleLang } from "@embra/i18n";

export const i18nLoader = (): Promise<I18n> => {
  const localeModules = import.meta.glob<boolean, string, Locale>("./locales/*.json", { import: "default" });

  const localeLoaders = Object.keys(localeModules).reduce(
    (loaders, path) => {
      if (localeModules[path]) {
        const langMatch = path.match(/\/([^/]+)\.json$/);
        if (langMatch) {
          loaders[langMatch[1]] = localeModules[path];
        }
      }
      return loaders;
    },
    {} as Record<LocaleLang, () => Promise<Locale>>,
  );

  const langs = Object.keys(localeLoaders);

  return I18n.preload(detectLang(langs) || (localeLoaders.en ? "en" : langs[0]), lang => localeLoaders[lang]());
};

React

  • <I18nProvider> to provide i18n context for descendant components.
  • useTranslate hook to subscribe and get the latest i18n.t.
  • useLang hook to subscribe and get the latest i18n.lang.
  • useI18n hook to subscribe and get the latest i18n instance.
  • <Trans> component to insert React elements into translation template messages.
import { I18n } from "@embra/i18n";
import { I18nProvider, useTranslate } from "@embra/i18n/react";

const i18n = new I18n("en", { en: { fruit: "apple" } });

const MyComponent = () => {
  const t = useTranslate();
  return <div>{t("fruit")}</div>;
};

const App = () => {
  return (
    <I18nProvider i18n={i18n}>
      <MyComponent />
    </I18nProvider>
  );
};

Cascading I18nProvider

You can nest multiple <I18nProvider>s to create cascading i18n contexts.

import { I18n } from "@embra/i18n";
import { I18nProvider, useTranslate } from "@embra/i18n/react";

const baseI18n = new I18n("en", { en: { confirm: "Confirm" } });
const loginI18n = new I18n("en", { en: { login: "Login" } });

const MyComponent = () => {
  const t = useTranslate();
  return (
    <div>
      <button>{t("confirm")}</button>
      <button>{t("login")}</button>
    </div>
  );
};

const App = () => {
  return (
    <I18nProvider i18n={baseI18n}>
      <I18nProvider i18n={loginI18n}>
        <MyComponent />
      </I18nProvider>
    </I18nProvider>
  );
};

Trans Component

To insert React elements into the translation message:

import { I18n, I18nProvider } from "@embra/i18n";
import { Trans, useTranslate } from "@embra/i18n/react";

const locales = {
  en: {
    author: "CRIMX",
    fruit: "apple",
    eat: "{{name}} eats {{fruit}}.",
  },
};

const i18n = new I18n("en", locales);

const MyComponent = () => {
  const t = useTranslate();

  return (
    <Trans message={t("eat")}>
      <strong data-t-slot="name">{t("author")}</strong>
      <i style={{ color: "red" }} data-t-slot="fruit">
        {t("fruit")}
      </i>
    </Trans>
  );
};

const App = () => {
  return (
    <I18nProvider i18n={i18n}>
      <MyComponent />
    </I18nProvider>
  );
};

↓Outputs:

<>
  <strong data-t-slot="name">CRIMX</strong> eats <i style={{ color: "red" }} data-t-slot="fruit">apple</i>.
<>

data-t-slot can be ignored if there is only one placeholder.

<Trans message="a{{b}}c">
  <h1>B</h1>
</Trans>

↓Outputs:

<>
  a<h1>B</h1>c
</>

Astro

For static Astro pages, create cached translation helpers and get t from the route language:

---
import { createStaticI18n } from "@embra/i18n/astro";

const locales = {
  en: {
    title: "Fruit stock",
    author: "CRIMX",
    fruit: "apple",
    eat: "{{name}} eats {{fruit}}.",
  },
  zh: {
    title: "水果库存",
    author: "CRIMX",
    fruit: "苹果",
    eat: "{{name}} 吃 {{fruit}}。",
  },
};

const { getT } = createStaticI18n({ locales, fallback: "en" });
const t = getT(Astro.params.lang);
---

<h1>{t("title")}</h1>

fallback is used as the default language when lang is omitted and as the fallback language when a key is missing.

Use the Astro <Trans> component when a translated message needs Astro slots:

---
import { createStaticI18n, Trans } from "@embra/i18n/astro";

const { getT } = createStaticI18n({ locales, fallback: "en" });
const t = getT(Astro.params.lang);
---

<Trans message={t("eat")}>
  <strong slot="name">{t("author")}</strong>
  <i slot="fruit" style="color: red">{t("fruit")}</i>
</Trans>

↓Outputs:

<strong>CRIMX</strong> eats <i style="color: red">apple</i>.

The default slot can be used when there is only one placeholder:

<Trans message="a{{b}}c">
  <strong>B</strong>
</Trans>

@embra/i18n/astro is rendered by Astro at build time or on the server. It does not add client-side language switching by itself; use a framework island if the translated component needs to update in the browser.

VSCode Extension

@embra/i18n is compatible with i18n Ally, a popular VSCode extension for i18n. You can use it to manage your locale files.

For AI Coding Agents

@embra/i18n includes an llms.txt quick guide for AI coding agents.

Add this to AGENTS.md or CLAUDE.md in projects that should implement i18n with @embra/i18n:

Implement internationalization with `@embra/i18n`. Usage reference: `node_modules/@embra/i18n/llms.txt`.

版本与发布记录

@embra/i18n 共发布 11 个版本,首次发布于 2025/10/06;过去 12 个月发布了 7 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.0latest2026/07/233 个月前
0.0.102026/06/025 个月前
0.0.92026/05/315 个月前
0.0.82026/05/295 个月前
0.0.72026/04/037 个月前
0.0.62026/03/118 个月前

关于 @embra/i18n 的常见问题

@embra/i18n 是什么?

A lightweight, reactive internationalization library.

如何安装 @embra/i18n?

在项目目录运行 npm install @embra/i18n,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@embra/reactivity(<=1)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@embra/i18n 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@embra/i18n 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@embra/i18n 可以商用吗?

@embra/i18n 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@embra/i18n 的下载量有多少?

根据 npm 官方下载统计,@embra/i18n 在 2026/10/14 – 2026/11/12 这 30 天内被下载 11,435 次,日均约 381 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@embra/i18n 还在维护吗?

最新版本 0.1.0 发布于 2026/07/23(3 个月前);至今共发布 11 个版本,其中过去 12 个月发布了 7 个;首次发布于 2025/10/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。