@k8ordo/i18n
Internationalization for React that works in both Server and Client Components
npm install @k8ordo/i18nsrc/i18n.tsimport { defineLocales } from '@k8ordo/i18n';
export const locales = defineLocales({
ja: { timeZone: 'Asia/Tokyo', dir: 'ltr' },
en: { timeZone: 'UTC', dir: 'ltr' },
});src/messages/nav.tsimport { message } from '@k8ordo/i18n';
export const home = message({ ja: 'ホーム', en: 'Home' });src/components/header.tsximport { home } from '../messages/nav';
export function Header() {
return (
<header>
<a href="/">{home()}</a>
</header>
);
}Calls without a provider or a hook
A message is a plain function that reads the locale where it is called. In the browser that is the locale at the start of the URL, such as en in /en/…; on the server it is the one locales.run or locales.paramsSchema set.
To switch language, navigate to the same page under another locale, such as from /ja/… to /en/….
src/components/page-title.tsximport { home } from '../messages/nav';
export function PageTitle() {
return <h1>{home()}</h1>;
}src/components/home-link.tsx'use client';
import { home } from '../messages/nav';
export function HomeLink() {
return <a href="/">{home()}</a>;
}Type errors for missing translations
Once Register carries the locale type, message requires text in every locale. Leave one out, and the declaration is a type error.
A message with values is a function in each locale. Annotate the arguments in one locale, and every other locale is checked against the same types.
src/messages/nav.tsimport { message } from '@k8ordo/i18n';
export const greeting = message({
ja: (name: string) => `こんにちは、${name}さん`,
en: (name) => `Hello, ${name}`,
});
export const save = message({ ja: '保存' });
No `en`: a type errorBundles with only the messages used
message has no side effects, so a bundler drops every message nothing imports. Only the messages Client Components use reach the browser.
Text rendered by a Server Component adds nothing to the client bundle. There is no namespace list to split dictionaries by.
src/components/greeting.tsx'use client';
import { greeting } from '../messages/nav';
export function Greeting({ name }: { name: string }) {
return <p>{greeting(name)}</p>;
}