Intlayerの今後のリリースに関する通知を受け取る
    作成:2025-06-18最終更新:2025-06-29

    Intlayer と React Native で国際化(i18n)を始める

    GitHub の アプリケーションテンプレート を参照してください。

    Intlayer とは?

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

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

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

    ステップ 1: 依存パッケージのインストール

    React Native プロジェクトから、以下のパッケージをインストールしてください:

    bash
    bash packageManager="npm"npm install intlayer react-intlayernpm install --save-dev react-native-intlayer

    パッケージ

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

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

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


    ステップ 2: Intlayer設定ファイルの作成

    プロジェクトのルート(または任意の便利な場所)にIntlayer設定ファイルを作成します。以下のような内容になるかもしれません:

    intlayer.config.ts
    /** * Locales型が利用できない場合は、tsconfig.jsonのmoduleResolutionを"bundler"に設定してみてください */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プロジェクトのデフォルトバンドラーです。IntlayerをMetroで使用するには、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-intlayer からの IntlayerProvider コンポーネントでラップする必要があります。

    また、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 defaultLocale={getDeviceLocale()}>      <Stack>tsx fileName="app/_layout.tsx" codeFormat="typescript"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 defaultLocale={getDeviceLocale()}>      <Stack>        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />      </Stack>    </IntlayerProviderContent>  );};export default RootLayout;

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

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

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

    • .content.json
    • .content.ts
    • .content.tsx
    • .content.js
    • .content.jsx
    • .content.mjs
    • .content.mjx
    • .content.cjs
    • .content.cjx
    • その他

    例(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({      en: "Welcome!",      fr: "Bienvenue!",      es: "¡Bienvenido!",    }),  },} satisfies Dictionary;export default homeScreenContent;

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


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

    子コンポーネントでuseIntlayerフックを使用して、ローカライズされたコンテンツを取得します。

    app/(tabs)/index.tsx
    import { Image, StyleSheet, Platform } from "react-native";import { useIntlayer } from "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;

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


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

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

    src/components/LocaleSwitcher.tsx
    import { type FC } from "react";import { View, Text, TouchableOpacity, StyleSheet } from "react-native";import { getLocaleName } from "intlayer";import { useLocale } from "react-intlayer";export const LocaleSwitcher: FC = () => {  const { setLocale, availableLocales } = useLocale();  return (    <View style={styles.container}>      {availableLocales.map((locale) => (        <TouchableOpacity          key={locale}          style={styles.button}          onPress={() => setLocale(locale)}        >          <Text style={styles.text}>{getLocaleName(locale)}</Text>        </TouchableOpacity>      ))}    </View>  );};const styles = StyleSheet.create({  container: {    flexDirection: "row",    justifyContent: "center",    alignItems: "center",    gap: 8,  },  button: {    paddingVertical: 6,    paddingHorizontal: 12,    borderRadius: 6,    backgroundColor: "#ddd",  },  text: {    fontSize: 14,    fontWeight: "500",    color: "#333",  },});

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

    詳細はuseLocaleのドキュメントをご覧ください。

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

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

    json5
    // tsconfig.json{  // ... 既存のTS設定  "include": [    "src", // ソースコード    ".intlayer/types/**/*.ts", // <-- 自動生成された型定義を含める    // ... 既に含めているその他のファイル  ],}

    これにより、以下の機能が利用可能になります:

    • 辞書キーのオートコンプリート
    • 存在しないキーにアクセスしたり型が不一致の場合に警告する型チェック

    Git設定

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

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

    VS Code拡張機能

    Intlayerの開発体験を向上させるために、公式のIntlayer VS Code拡張機能をインストールできます。

    VS Codeマーケットプレイスからインストール

    この拡張機能は以下を提供します:

    • 翻訳キーのオートコンプリート
    • 翻訳が欠落している場合のリアルタイムエラー検出
    • 翻訳内容のインラインプレビュー
    • 翻訳の作成や更新を簡単に行うためのクイックアクション

    拡張機能の使い方の詳細については、Intlayer VS Code拡張機能のドキュメントを参照してください。


    さらに進む

    • ビジュアルエディター:翻訳を視覚的に管理するために、Intlayerビジュアルエディターを使用してください。
    • CMS統合: 辞書コンテンツを外部化し、CMSから取得することも可能です。
    • CLIコマンド: 翻訳の抽出欠落キーの確認などのタスクには、Intlayer CLIを活用してください。

    Intlayerを通じて、完全なi18n機能を備えたReact Nativeアプリの開発をお楽しみください!


    ドキュメント履歴

    • 5.5.10 - 2025-06-29: 履歴初期化
    Intlayerの今後のリリースに関する通知を受け取る