IntlayerとReact Nativeでの国際化(i18n)の始め方

    Intlayerとは?

    Intlayerは、現代のアプリケーションにおける多言語対応を簡素化する革新的なオープンソースの国際化(i18n)ライブラリです。これは多くのJavaScript/TypeScript環境で動作し、React Nativereact-intlayerパッケージを介して)も含まれます。

    Intlayerを使用すると、以下が可能です:

    • コンポーネントレベルで宣言的な辞書を使用して、簡単に翻訳を管理できます。
    • 自動生成された型でTypeScriptサポートを確保できます。
    • UI文字列を含むコンテンツを動的にローカライズできます(React for webではHTMLメタデータなどもローカライズ可能)。
    • 動的なロケール検出や切り替えなどの高度な機能を活用できます。

    ステップ1: 依存関係をインストールする

    React Nativeプロジェクトから、以下のパッケージをインストールします:

    bash
    npm install intlayer react-intlayer react-native-intlayer

    パッケージ

    • intlayer
      設定、辞書コンテンツ、型生成、CLIコマンドのためのコアi18nツールキット。

    • react-intlayer
      React統合用で、React Nativeでロケールの取得や切り替えに使用するコンテキストプロバイダーとReactフックを提供します。

    • react-native-intlayer
      React Native統合用で、IntlayerをReact Nativeバンドラーと統合するためのMetroプラグインを提供します。


    ステップ2: Intlayerの設定を作成する

    プロジェクトのルート(または便利な場所)にIntlayer設定ファイルを作成します。以下のようになります:

    intlayer.config.ts
    import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = {  internationalization: {    locales: [      Locales.ENGLISH,      Locales.FRENCH,      Locales.SPANISH,      // ... 必要な他のロケールを追加    ],    defaultLocale: Locales.ENGLISH,  },};export default config;

    この設定内で以下を行うことができます:

    • サポートするロケールのリストを設定します。
    • デフォルトのロケールを設定します。
    • 後で、より高度なオプション(例:ログ、カスタムコンテンツディレクトリなど)を追加できます。
    • 詳細はIntlayer設定ドキュメントをご覧ください。

    ステップ3: Metroプラグインを追加する

    MetroはReact Nativeのバンドラーです。react-native initコマンドで作成されたReact Nativeプロジェクトのデフォルトバンドラーです。MetroでIntlayerを使用するには、metro.config.jsファイルにプラグインを追加する必要があります:

    metro.config.js
    const { getDefaultConfig } = require("expo/metro-config");const { configMetroIntlayer } = require("react-native-intlayer/metro");module.exports = (async () => {  const defaultConfig = getDefaultConfig(__dirname);  return await configMetroIntlayer(defaultConfig);})();

    ステップ4: Intlayerプロバイダーを追加する

    アプリケーション全体でユーザーの言語を同期させるために、react-intlayerIntlayerProviderコンポーネントでルートコンポーネントをラップする必要があります。

    また、Intlayerが正しく動作するようにするために、index.jsファイルにintlayerPolyfill関数を追加する必要があります。

    app/_layout.tsx
    import { Stack } from "expo-router";import { getLocales } from "expo-localization";import { IntlayerProviderContent } from "react-intlayer";import { intlayerPolyfill } from "react-native-intlayer";import { type FC } from "react";intlayerPolyfill();const getDeviceLocale = () => getLocales()[0]?.languageTag;const RootLayout: FC = () => {  return (    <IntlayerProviderContent locale={getDeviceLocale()}>      <Stack>        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />      </Stack>    </IntlayerProviderContent>  );};export default RootLayout;

    ステップ5: コンテンツを宣言する

    プロジェクト内の任意の場所(通常はsrc/内)にコンテンツ宣言ファイルを作成します。Intlayerがサポートする任意の拡張形式を使用できます:

    • .content.ts
    • .content.mjs
    • .content.cjs
    • .content.json
    • など

    例(React Native用のTSXノードを使用したTypeScript):

    src/app.content.tsx
    import { t, type Dictionary } from "intlayer";import type { ReactNode } from "react";/** * "app"ドメイン用のコンテンツ辞書 */import { t, type Dictionary } from "intlayer";const homeScreenContent = {  key: "home-screen",  content: {    title: t({      ja: "ようこそ!",      en: "Welcome!",      fr: "Bienvenue!",      es: "¡Bienvenido!",    }),  },} satisfies Dictionary;export default homeScreenContent;

    コンテンツ宣言の詳細については、Intlayerのコンテンツドキュメントをご覧ください。


    ステップ4: コンポーネントでIntlayerを使用する

    react-intlayerからIntlayerProviderルートまたはトップレベルのコンポーネントをラップします。その後、子コンポーネントでuseIntlayerフックを使用してローカライズされたコンテンツを取得します。

    app/(tabs)/index.tsx
    import { Image, StyleSheet, Platform } from "react-native";import { useIntlayer } from "react-intlayer";import { HelloWave } from "@/components/HelloWave";import ParallaxScrollView from "@/components/ParallaxScrollView";import { ThemedText } from "@/components/ThemedText";import { ThemedView } from "@/components/ThemedView";import { type FC } from "react";const HomeScreen = (): FC => {  const { title, steps } = useIntlayer("home-screen");  return (    <ParallaxScrollView      headerBackgroundColor={{ light: "#A1CEDC", dark: "#1D3D47" }}      headerImage={        <Image          source={require("@/assets/images/partial-react-logo.png")}          style={styles.reactLogo}        />      }    >      <ThemedView style={styles.titleContainer}>        <ThemedText type="title">{title}</ThemedText>        <HelloWave />      </ThemedView>    </ParallaxScrollView>  );};const styles = StyleSheet.create({  titleContainer: {    flexDirection: "row",    alignItems: "center",    gap: 8,  },});export default HomeScreen;

    文字列ベースのプロップス(例: ボタンのtitleTextコンポーネントのchildren)でcontent.someKeyを使用する場合、実際の文字列を取得するにはcontent.someKey.valueを呼び出してください


    (オプション)ステップ5: アプリのロケールを変更する

    コンポーネント内からロケールを切り替えるには、useLocaleフックのsetLocaleメソッドを使用します:

    src/components/LocaleSwitcher.tsx
    import { type FC } from "react";import { Button } from "react-native";import { Locales } from "intlayer";import { useLocale } from "react-intlayer";export const LocaleSwitcher: FC = () => {  const { setLocale } = useLocale();  return (    <Button      title="フランス語に切り替え"      onPress={() => {        setLocale(Locales.FRENCH);      }}    />  );};

    これにより、Intlayerコンテンツを使用するすべてのコンポーネントが再レンダリングされ、新しいロケールの翻訳が表示されます。

    詳細については、useLocaleドキュメントをご覧ください。

    TypeScriptの設定(TypeScriptを使用している場合)

    Intlayerは、補完機能を向上させ、翻訳エラーを検出するために、隠しフォルダ(デフォルトでは.intlayer)に型定義を生成します:

    json5
    // tsconfig.json{  // ... 既存のTS設定  "include": [    "src", // ソースコード    ".intlayer", // <-- 自動生成された型を含める    // ... 既存の他の設定  ],}

    これにより、以下の機能が有効になります:

    • 辞書キーの補完機能
    • 存在しないキーへのアクセスや型の不一致を警告する型チェック

    Gitの設定

    Intlayerによって自動生成されたファイルをコミットしないようにするには、以下を.gitignoreに追加してください:

    plaintext
    # Intlayerによって生成されたファイルを無視.intlayer

    さらに進む

    • ビジュアルエディターIntlayer Visual Editorを使用して翻訳を視覚的に管理します。
    • CMS統合:辞書コンテンツを外部化し、CMSから取得することもできます。
    • CLIコマンドIntlayer CLIを使用して、翻訳の抽出や不足しているキーの確認などのタスクを実行します。

    Intlayerを活用して、React Nativeアプリを完全なi18n対応で構築してください!

    このドキュメントを改善するアイデアがある場合は、GitHubでプルリクエストを送信することで自由に貢献してください。

    ドキュメントへのGitHubリンク