Hono を Lefine で設定する
- 01
パッケージをインストール
Hono とサーバーアダプターを追加します。ほかに必要なものはありません。
terminalbashnpm install hono lefine && npx lefine strings pull -o locales - 02
i18n シングルトンを作成
モジュールスコープで一度だけ生成します。メッセージキャッシュはすべてのリクエストで共有されます。
src/i18n.tsimport { createTranslator } from 'lefine/strings';import en from '../locales/en.json';import de from '../locales/de.json';// Module scope, not per request: the files are read once.export const files = { en, de } as const;export type Locale = keyof typeof files;export const defaultLocale: Locale = 'en';export const translatorFor = (locale: Locale) => createTranslator({ locale, messages: files[locale] }); - 03
ミドルウェアを組み込む
app.use の後は、すべてのハンドラーがコンテキストから locale と t を読み取れます。
src/index.tsimport { Hono } from 'hono';import { files, defaultLocale, translatorFor, type Locale } from './i18n';const app = new Hono<{ Variables: { locale: string; t: ReturnType<typeof translatorFor> };}>();app.use('*', async (c, next) => { const asked = c.req.header('accept-language')?.slice(0, 2) ?? ''; const locale = (asked in files ? asked : defaultLocale) as Locale; c.set('locale', locale); c.set('t', translatorFor(locale)); await next();});app.get('/users/:id', (c) => { const t = c.get('t'); return c.json({ error: t('errors.notFound') }, 404);});export default app;