@k8ordo/i18n

はじめる

日本語と英語の文言を持つアプリを作ります。ロケールを定義し、文言をServer ComponentとClient Componentに表示します。

このページの内容

インストール

bash
npm install @k8ordo/i18n

次の環境で動きます。

  • TypeScriptで書くなら、TypeScript 7以上

エージェント向けのガイドはnode_modules/@k8ordo/i18n/docs/GUIDE.mdに入っています。AGENTS.mdなどからこのパスを参照させてください。

サーバーでは、process.getBuiltinModuleでAsyncLocalStorageを取り出せるランタイムが必要です。Node 24はこの条件を満たします。

ロケールの定義

src/i18n.ts
import { defineLocales } from '@k8ordo/i18n';
import type { LocaleOf } from '@k8ordo/i18n';

export const locales = defineLocales({
  ja: { timeZone: 'Asia/Tokyo', dir: 'ltr' },
先頭に書いたロケールが既定のロケール
  en: { timeZone: 'UTC', dir: 'ltr' },
});

declare module '@k8ordo/i18n' {
  interface Register {
    locale: LocaleOf<typeof locales>;
  }
}

アプリが扱うロケールをdefineLocalesで書きます。ロケールごとに、日付を表示するタイムゾーン(timeZone)と文字の向き(dir)を添えます。

Registerは、ロケールの型をパッケージに伝える宣言です。これを書くと、messageがすべてのロケールの文を求めるようになります。@k8ordo/frameworkのアプリでは、src/i18n.tsがexportするlocalesからRegisterが生成されるので、この宣言は書きません。詳しくは@k8ordo/frameworkのルーティングを見てください。

既定のロケールの選び方やタイムゾーンの決め方はロケールを見てください。

文言の定義

src/messages/home.ts
import { message } from '@k8ordo/i18n';

export const title = message({ ja: 'ようこそ', en: 'Welcome' });

export const nameLabel = message({ ja: '名前', en: 'Name' });

export const greeting = message({
  ja: (name: string) => `こんにちは、${name}さん`,
`en`の`name`の型は`ja`の注釈から推論される
  en: (name) => `Hello, ${name}`,
});

文言はmessageで1つずつ書き、ロケールごとの文を並べます。値を差し込む文言は、ロケールごとの関数にします。

enの関数は、jaと同じ引数の型で書きます。

Server Componentでの描画

src/components/welcome.tsx
import { title } from '../messages/home';
import { Greeting } from './greeting';

export function Welcome() {
  return (
    <main>
      <h1>{title()}</h1>
呼ぶだけで、今のロケールの文が返る
      <Greeting />
    </main>
  );
}

サーバーでは、今の非同期コンテキストに設定されたロケールの文を返します。何も設定されていなければ、既定のロケールの文(ようこそ)を返します。

ロケールを設定するのはlocales.runとlocales.paramsSchemaです。使い方は今のロケールを見てください。

@k8ordo/frameworkでは、[locale]のレイアウトからparamsSchemaをexportすると、/en/…のページが英語で描画されます。詳しくは@k8ordo/frameworkのルーティングを見てください。

Client Componentでの描画

src/components/greeting.tsx
'use client';

import { useState } from 'react';

import { greeting, nameLabel } from '../messages/home';

export function Greeting() {
  const [name, setName] = useState('k8o');

  return (
    <div>
      <label>
        {nameLabel()}
        <input
          onChange={(event) => {
            setName(event.currentTarget.value);
          }}
          value={name}
        />
      </label>
      <p>{greeting(name)}</p>
値を差し込む文言は、引数を付けて呼ぶ
    </div>
  );
}

Client Componentでも書き方は同じです。ブラウザではURLの先頭の区間を読むので、プロバイダでロケールを渡す必要も、フックで読み出す必要もありません。

Server ComponentからClient Componentへ文言をpropsで渡すときは、呼んだ結果の文字列を渡します。関数はClient Componentへのpropsとして渡せません。詳しくは文言を見てください。

k8ordo

Baselineに入った機能を、制限なく使うReactのライブラリ群。