Lingui.jsは、JavaScriptおよびReactアプリケーション向けの軽量かつ強力なi18nフレームワークです。翻訳カタログには業界標準のPO (Portable Object) ファイルを使用し、クリーンな開発者体験のために強力なコンパイル時マクロを使用し、2 kB未満の最適化されたバンドルを生成します。このガイドでは、プロジェクトのセットアップからPOファイルのワークフロー、複数形の形式、l10n.devによる翻訳の自動化までを網羅しています。
Lingui.jsは、開発者体験、パフォーマンス、プロフェッショナルな翻訳ワークフローの組み合わせにおいて、JavaScript i18nライブラリの中でも際立っています。
Linguiのコアパッケージと開発ツールをインストールします。ランタイムパッケージ(@lingui/coreと@lingui/react)は本番環境で必要ですが、CLI、Viteプラグイン、Babelマクロは開発時のみ必要です。
npm install @lingui/core @lingui/react
npm install --save-dev @lingui/cli @lingui/vite-plugin @lingui/babel-plugin-lingui-macroLinguiには、Lingui設定(ロケールとカタログパスの定義)とビルドツール設定(コンパイル時マクロの有効化)の2つの設定ファイルが必要です。
プロジェクトのルートにlingui.config.jsファイルを作成します。ここでソースロケール、ターゲットロケール、POカタログの保存場所、カタログ形式を定義します。PO形式がデフォルトであり、推奨される選択肢です。
// lingui.config.js
import { defineConfig } from "@lingui/cli";
import { formatter } from "@lingui/format-po";
export default defineConfig({
sourceLocale: "en",
locales: ["en", "fr", "de", "ja", "es", "zh-CN"],
catalogs: [
{
path: "<rootDir>/src/locales/{locale}/messages",
include: ["src"],
},
],
format: formatter({ lineNumbers: false }),
});Viteを使用している場合は、BabelマクロとともにLinguiプラグインをReactプラグインと並べて追加します。これにより、コンパイル時のメッセージ変換とオンザフライでのカタログコンパイルが可能になります。
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { lingui } from "@lingui/vite-plugin";
export default defineConfig({
plugins: [
react({
babel: {
plugins: ["@lingui/babel-plugin-lingui-macro"],
},
}),
lingui(),
],
});PO (Portable Object) は、GNU gettextシステムに由来する業界標準の翻訳ファイル形式です。Linguiは、翻訳ツール、TMSプラットフォーム、世界中のプロの翻訳者に広くサポートされているため、デフォルトのカタログ形式としてPOを使用しています。
#: src/components/WelcomeBanner.js:6
msgid "Welcome to our platform"
msgstr ""
#: src/components/WelcomeBanner.js:8
msgid "Hello {userName}, check out your <0>dashboard</0> to get started."
msgstr ""
#: src/components/CartSummary.js:5
msgid "{itemCount, plural, =0 {Your cart is empty} one {You have # item in your cart} other {You have # items in your cart}}"
msgstr ""翻訳後、各msgstrにはローカライズされたバージョンが入力されます。Linguiは、ICU MessageFormat構文、Reactコンポーネントのインデックス付きタグ、プレースホルダー変数をすべての翻訳を通じて保持します。
#: src/components/WelcomeBanner.js:6
msgid "Welcome to our platform"
msgstr "Bienvenue sur notre plateforme"
#: src/components/WelcomeBanner.js:8
msgid "Hello {userName}, check out your <0>dashboard</0> to get started."
msgstr "Bonjour {userName}, consultez votre <0>tableau de bord</0> pour commencer."
#: src/components/CartSummary.js:5
msgid "{itemCount, plural, =0 {Your cart is empty} one {You have # item in your cart} other {You have # items in your cart}}"
msgstr "{itemCount, plural, =0 {Votre panier est vide} one {Vous avez # article dans votre panier} other {Vous avez # articles dans votre panier}}"POカタログをlocalesディレクトリ内に整理し、ロケールごとに1つのサブフォルダーを作成します。Lingui CLIは、抽出中にこれらのファイルを自動的に作成および更新します。コンパイルされたJSモジュールはビルド時に生成されるため、手動で編集しないでください。
src/
├── locales/
│ ├── en/
│ │ └── messages.po ← Source (English)
│ ├── fr/
│ │ └── messages.po ← French
│ ├── de/
│ │ └── messages.po ← German
│ ├── ja/
│ │ └── messages.po ← Japanese
│ ├── es/
│ │ └── messages.po ← Spanish
│ └── zh-CN/
│ └── messages.po ← Chinese Simplified
├── components/
├── i18n.ts
├── App.tsx
└── ...Linguiはメッセージをマークするための2つの主要なアプローチを提供します。コンポーネントコンテンツ用のJSXマクロと、命令的な文字列用のuseLinguiフックです。どちらも最適化された出力を生成するコンパイル時マクロです。
JSXコンテンツをTransマクロでラップして翻訳可能にします。変数、HTML要素、Reactコンポーネントが完全にサポートされており、マクロはそれらを自動的にインデックス付きタグを持つICU MessageFormatに変換します。
import { Trans } from "@lingui/react/macro";
function WelcomeBanner({ userName }) {
return (
<div>
<h1>
<Trans>Welcome to our platform</Trans>
</h1>
<p>
<Trans>
Hello {userName}, check out your <a href="/dashboard">dashboard</a> to
get started.
</Trans>
</p>
</div>
);
}JSX外の文字列(アラートメッセージ、ariaラベル、属性値、または任意の命令的コード)には、タグ付きテンプレートリテラルでuseLinguiマクロフックを使用します。
import { useLingui } from "@lingui/react/macro";
function NotificationButton() {
const { t } = useLingui();
const showAlert = () => {
alert(t`Your changes have been saved.`);
};
return (
<button onClick={showAlert} aria-label={t`Save changes`}>
<Trans>Save</Trans>
</button>
);
}Linguiは、自動生成されたID(ソースメッセージの内容から派生)と明示的なID(開発者が定義したキー)の2つのアプローチをサポートしています。どちらのアプローチもPOファイルで機能します。
import { Trans } from "@lingui/react/macro";
// Auto-generated ID (from message content)
<Trans>Welcome to our platform</Trans>
// Explicit ID (developer-defined key)
<Trans id="nav.welcome">Welcome to our platform</Trans>任意のマクロでcommentプロップを使用して記述を追加します。このコメントは翻訳者向けメモとしてPOファイルに抽出され、メッセージがどこにどのように表示されるかについての重要なコンテキストを提供します。
import { Trans } from "@lingui/react/macro";
<Trans comment="Shown on the homepage hero section above the fold">
Start building with confidence
</Trans>Linguiは複数形の形式にICU MessageFormatを使用しており、すべてのCLDR複数形カテゴリをサポートしています。Pluralマクロを使用すると、JSX内で異なる複数形の形式を簡単に処理できます。
import { Plural } from "@lingui/react/macro";
function CartSummary({ itemCount }) {
return (
<p>
<Plural
value={itemCount}
_0="Your cart is empty"
one="You have # item in your cart"
other="You have # items in your cart"
/>
</p>
);
}メッセージを抽出してコンパイルした後、i18nインスタンスをセットアップし、アプリをI18nProviderでラップします。
コンパイルされたメッセージカタログを動的にロードするi18nモジュールを作成します。Lingui Viteプラグインを使用すると、POファイルの直接インポートが可能になり、開発中にオンザフライでコンパイルされます。
// src/i18n.ts
import { i18n } from "@lingui/core";
export async function loadCatalog(locale: string) {
const { messages } = await import(`./locales/${locale}/messages.po`);
i18n.load(locale, messages);
i18n.activate(locale);
}
// Initialize with default locale
loadCatalog("en");
export default i18n;アプリ全体をI18nProviderでラップし、Reactコンテキストを通じてすべてのコンポーネントで翻訳を利用できるようにします。
// src/App.tsx
import { I18nProvider } from "@lingui/react";
import { i18n } from "./i18n";
function App() {
return (
<I18nProvider i18n={i18n}>
<YourAppContent />
</I18nProvider>
);
}言語の切り替えは簡単です。新しいカタログをロードしてロケールをアクティブにすると、Reactが翻訳されたすべてのコンテンツを自動的に再レンダリングします。完全な言語スイッチャーコンポーネントは以下の通りです。
import { useState } from "react";
import { loadCatalog } from "./i18n";
import { Trans } from "@lingui/react/macro";
const LANGUAGES = {
en: "English",
fr: "Français",
de: "Deutsch",
ja: "日本語",
es: "Español",
};
function LanguageSwitcher() {
const [currentLocale, setCurrentLocale] = useState("en");
const handleChange = async (locale: string) => {
await loadCatalog(locale);
setCurrentLocale(locale);
};
return (
<select
value={currentLocale}
onChange={(e) => handleChange(e.target.value)}
>
{Object.entries(LANGUAGES).map(([code, name]) => (
<option key={code} value={code}>
{name}
</option>
))}
</select>
);
}LinguiのCLIは、翻訳ワークフローの核となる2つの主要コマンドを提供します。ソースコードからPOカタログにメッセージをプルするextractと、POファイルを本番用の最適化されたJavaScriptモジュールに変換するcompileです。
# Extract messages from source code into PO catalogs
npx lingui extract
# Translate your PO files (manually, with a TMS, or with AI)
# Compile PO catalogs into optimized JS modules for production
npx lingui compilel10n.devはPOファイルのネイティブサポートを提供しており、Lingui.jsプロジェクトの完璧なパートナーです。ソースPOカタログをアップロードすると、正確に翻訳されたファイルが返されます。
ai-l10n npmパッケージを使用して、コマンドラインから、またはCI/CDパイプラインの一部としてLingui POカタログを翻訳します。一度インストールすれば、単一のコマンドで任意の数の言語に翻訳できます。
# Install the CLI
npm install ai-l10n
# Translate your source PO file to multiple languages
npx ai-l10n translate src/locales/en/messages.po \
--languages fr,de,ja,zh-CN,es,koai-l10nをLinguiビルドプロセスに直接組み込むことで、翻訳が常に最新の状態になるようにします。抽出、翻訳、コンパイルを単一のワークフローにまとめます。
extract、translate、compileをスクリプトとして追加し、それらを連結します。i18nスクリプトは完全なパイプラインを実行します。出荷前に翻訳が常に最新であることを保証するためにprebuildで使用してください。
{
"scripts": {
"extract": "lingui extract",
"compile": "lingui compile",
"translate": "ai-l10n translate src/locales/en/messages.po --languages fr,de,ja,zh-CN,es,ko --update",
"i18n": "npm run extract && npm run translate && npm run compile",
"prebuild": "npm run i18n",
"build": "vite build",
"dev": "vite"
}
}チームでMakeを使用している場合は、抽出、翻訳、コンパイルを適切な依存関係を持つ個別のターゲットとして宣言します。
LANGUAGES = fr,de,ja,zh-CN,es,ko
extract:
npx lingui extract
translate:
npx ai-l10n translate src/locales/en/messages.po --languages $(LANGUAGES) --update
compile:
npx lingui compile
i18n: extract translate compile
dev: i18n
npx vite
build: i18n
npx vite buildCI/CD統合、増分更新、複数ファイルにわたる一括翻訳、GitHubアクションのワークフロー例については、以下を参照してください。ローカリゼーション自動化ガイド
l10n.devのVS Code拡張機能を使用すると、エディタ内で直接POファイル翻訳を行えます。VS Codeを離れることなくLinguiカタログを翻訳できます。
世界中のユーザーにリーチする準備はできましたか?l10n.devワークスペースで直接Lingui POファイルを翻訳するか、npm CLIで自動化するか、VS Code内で翻訳することができます。
l10n.devを使用してLingui.jsプロジェクトをローカライズしていただきありがとうございます!🚀
このガイドが役に立った場合は、POファイルを使用してアプリケーションを国際化する必要がある他のReact開発者と共有してください。
JavaScriptアプリケーションをよりアクセスしやすく、世界中のユーザーに対応したものにしていきましょう。