Angularで国際化(i18n)を使用する方法

提供:Dev Guides
移動先:案内検索

序章

国際化は、アプリケーションで複数の言語をサポートするプロセスです。

これは、 ngx-translate などのサードパーティライブラリを介してAngularアプリケーションで実行できます。または、組み込みのi18n機能を使用することもできます。

注:「i18n」はヌメロニムです。ここで、「18」は単語の最初の文字(「I」)と最後の文字(「N」)の間の文字数を表します。 「国際化」。 アプリケーションを開発するときに、アクセシビリティのヌメロニムである「a11y」に遭遇することもあります。


このチュートリアルでは、Angularアプリケーションで組み込みのi18n機能を使用する方法を学習します。

前提条件

このチュートリアルを完了するには、次のものが必要です。

このチュートリアルは、ノードv14.13.1、npm v6.14.8、angular v10.1.6、および@angular/localizev10.1.6で検証されました。

ステップ1—プロジェクトの設定

@ angle / cli を使用して、新しいAngularプロジェクトを作成できます。

ターミナルウィンドウで、次のコマンドを使用します。

npx @angular/cli new angular-internationalization-example --style=css --routing=false --skip-tests

これにより、スタイルが「CSS」(「Sass」、「Less」、「Stylus」ではなく)に設定され、ルーティングがなく、テストがスキップされる新しいAngularプロジェクトが構成されます。

新しく作成されたプロジェクトディレクトリに移動します。

cd angular-internationalization-example

翻訳プロジェクトの基礎を作成するには、コードエディタでapp.component.htmlを開き、コードを次の行に置き換えます。

src / app / app.component.html

<section>
  <article>
    <h1>Under Construction!</h1>
    <p>This page is under construction.</p>
  </article>
</section>

このコードは、"Under Construction!"および"This page is under construction"メッセージを表示します。

次に、app.component.cssを開き、コードを次の行に置き換えます。

sec / app / app.component.css

section {
  background: #8e2de2; /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #4a00e0, #8e2de2); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #4a00e0, #8e2de2);
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

article {
  border: 1px solid white;
  box-shadow: 1px 1px 100px 10px rgba(0, 0, 0, 0.8);
  color: white;
  padding: 40px;
  text-align: center;
}

このコードは、フレックスボックス、ビューポートの高さの値、線形グラデーションの背景、およびボックスシャドウを使用して、"Under Construction!"メッセージを画面の中央に配置します。

次に、styles.cssを開き、コードを次の行に置き換えます。

src / styles.css

html,
body {
  padding: 0;
  margin: 0;
}

これにより、ブラウザのユーザースタイルがデフォルトで配置する傾向のあるパディングとマージンが削除されます。 これらのスタイルを使用することにより、デフォルトが異なるすべてのブラウザー間で一貫したベースラインを作成できます。

ターミナルウィンドウで、アプリケーションを起動します。

npm start

Webブラウザでlocalhost:4200にアクセスします。

アプリケーションが期待どおりに動作していることを確認できたら、翻訳するメッセージの抽出を開始できます。

ステップ2—xi18nを使用してmessages.xlfを抽出する

アプリケーション内で翻訳したいテキストをマークすることから始めましょう。 このチュートリアルでは、アプリケーションをフランス語(fr)とドイツ語(de)に翻訳し、Google翻訳で翻訳を提供します。

翻訳するすべてのテキストにi18nディレクティブを追加します。

src / app / app.component.html

<section>
  <article>
    <h1 i18n>Under Construction!</h1>
    <p i18n>This page is under construction.</p>
  </article>
</section>

次に、AngularCLIを使用してマークされたアイテムをapp.component.htmlからmessages.xlfファイルに抽出するnpmスクリプトをpackage.json内に作成する必要があります。

package.json

{
  // ...
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "i18n:extract": "ng xi18n"
  },
  // ...
}

これを追加した後、ターミナルウィンドウで新しいスクリプトを実行します。

npm run i18n:extract

次に、messages.xlfを開くと、次のようなものが表示されます。

messages.xlf

<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
  <file source-language="en-US" datatype="plaintext" original="ng2.template">
    <body>
      <trans-unit id="48a16ab522feaff81571155668deb1a4304291f4" datatype="html">
        <source>Under Construction!</source>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">3</context>
        </context-group>
      </trans-unit>
      <trans-unit id="84c778d7a95cb5dc26c9cc9feb5b7abb4d295792" datatype="html">
        <source>This page is under construction.</source>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">4</context>
        </context-group>
      </trans-unit>
    </body>
  </file>
</xliff>

翻訳が必要な(つまり、i18nディレクティブがある)アイテムごとに、trans-unitが作成されます。

この構造を使用して、翻訳に関する詳細情報を提供することもできます。 これは、各メッセージをサードパーティによって翻訳してもらい、より多くの情報を提供したい場合に役立ちます。

app.component.html内で、i18nアイテムを説明で更新します。

src / app / app.component.html

<article>
  <h1 i18n="Title for the under construction card">Under Construction!</h1>
  <p i18n="A description for the under construction card.">This page is under construction.</p>
</article>

パイプ文字(|)を使用して、これにコンテキストをさらに追加できます。 これにより、アイテムの意味が得られ、同じの意味を持つ各アイテムの翻訳は同じになります。

src / app / app.component.html

<article>
  <h1 i18n="Card Header|Title for the under construction card">Under Construction!</h1>
  <p i18n="Card Descritpion|A description for the under construction card.">This page is under construction.</p>
</article>

また、アットマーク文字(@@)を2つ使用して、各i18nアイテムにid を指定し、翻訳を生成するときに永続性を適用することもできます。

src / app / app.component.html

<article>
  <h1 i18n="Card Header|Title for the under construction card@@constructionHeader">Under Construction!</h1>
  <p i18n="Card Descritpion|A description for the under construction card.@@constructionDescription">This page is under construction.</p>
</article>

もう一度翻訳を作成しましょう。

npm run int:extract

アイテムは、 id意味、および説明で更新されます。

messages.xlf

<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
  <file source-language="en-US" datatype="plaintext" original="ng2.template">
    <body>
      <trans-unit id="constructionHeader" datatype="html">
        <source>Under Construction!</source>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">3</context>
        </context-group>
        <note priority="1" from="description">Title for the under construction card</note>
        <note priority="1" from="meaning">Card Header</note>
      </trans-unit>
      <trans-unit id="constructionDescription" datatype="html">
        <source>This page is under construction.</source>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">4</context>
        </context-group>
        <note priority="1" from="description">A description for the under construction card.</note>
        <note priority="1" from="meaning">Card Descritpion</note>
      </trans-unit>
    </body>
  </file>
</xliff>

複数のtrans-unit、説明、意味、およびIDを含むmessages.xlfファイルを作成したら、フランス語とドイツ語の翻訳の作成を開始できます。

ステップ3—フランス語とドイツ語の翻訳を作成する

デフォルトでは、Angularはすべてが「アメリカ英語」(en-US)ロケールであると見なします。 他のロケールを追加し、それらをサポートするように構成を更新する必要があります。

これらのロケールは、ロケール識別子(ID)によって参照されます。 たとえば、「アメリカ英語」はIDen-USを使用します。 最初の2文字(en)は、「英語」のロケール識別子を割り当てます。 最後の2文字(US)は、「米国」のロケール拡張子を割り当てます。 これらの識別子は、BCP47によって確立されたルールから派生しています。

プロジェクトディレクトリが乱雑にならないようにするには、翻訳ファイルを新しいディレクトリに保存すると便利な場合があります。 output-pathオプションをi18n:extractスクリプトに提供して、localesディレクトリに配置できます。

package.json

{
  // ...
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "i18n:extract": "ng xi18n --output-path src/locale"
  },
  // ...
}

既存のmessages.xlfファイルを削除します。

rm messages.xlf

そして、i18n:extractコマンドを再実行します。

npm run i18n:extract

スクリプトの変更が期待どおりに機能し、localesディレクトリにmessages.xlfファイルがあることを確認したら、翻訳用にtargetの追加を開始できます。

フランス語

まず、messages.xlfmessages.fr.xlfにコピーします。

cp src/locale/messages.xlf src/locale/messages.fr.xlf

次に、アイテムごとにtargetを追加します。

src / locale / messages.fr.xlf

<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
  <file source-language="en-US" datatype="plaintext" original="ng2.template">
    <body>
      <trans-unit id="constructionHeader" datatype="html">
        <source>Under Construction!</source>
        <target>En construction</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">3</context>
        </context-group>
        <note priority="1" from="description">Title for the under construction card</note>
        <note priority="1" from="meaning">Card Header</note>
      </trans-unit>
      <trans-unit id="constructionDescription" datatype="html">
        <source>This page is under construction.</source>
        <target>Cette page est en construction</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">4</context>
        </context-group>
        <note priority="1" from="description">A description for the under construction card.</note>
        <note priority="1" from="meaning">Card Descritpion</note>
      </trans-unit>
    </body>
  </file>
</xliff>

trans-unitには、英語のsourceメッセージとフランス語のtargetメッセージが含まれるようになりました。

ドイツ人

次に、messages.xlfmessages.de.xlfにコピーします。

cp src/locale/messages.xlf src/locale/messages.de.xlf

次に、アイテムごとにtargetを追加します。

src / locale / messages.de.xlf

<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
  <file source-language="en-US" datatype="plaintext" original="ng2.template">
    <body>
      <trans-unit id="constructionHeader" datatype="html">
        <source>Under Construction!</source>
        <target>Im Bau</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">3</context>
        </context-group>
        <note priority="1" from="description">Title for the under construction card</note>
        <note priority="1" from="meaning">Card Header</note>
      </trans-unit>
      <trans-unit id="constructionDescription" datatype="html">
        <source>This page is under construction.</source>
        <target>Diese Seite befindet sich im Aufbau</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">4</context>
        </context-group>
        <note priority="1" from="description">A description for the under construction card.</note>
        <note priority="1" from="meaning">Card Descritpion</note>
      </trans-unit>
    </body>
  </file>
</xliff>

trans-unitには、英語のsourceメッセージとドイツ語のtargetメッセージが含まれるようになりました。

ステップ4—フランス語とドイツ語のビルドを作成する

localeに基づいて翻訳されたアプリケーションのバージョンがあります。

Angular CLIを使用して、サポートするロケールごとに特定のビルドを生成できます。

まず、@angular/localizeをインストールする必要があります。

./node_modules/@angular/cli/bin/ng add @angular/localize

コードエディタでangular.jsonを開き、frおよびdeロケールを追加します。

angle.json

{
  "projects": {
    "angular-internationalization-example": {
      // ...
      "i18n": {
        "sourceLocale": "en-US",
        "locales": {
          "fr": {
            "translation": "src/locale/messages.fr.xlf",
            "baseHref": ""
          },
          "de": {
            "translation": "src/locale/messages.de.xlf",
            "baseHref": "" 
          }
        }
      },
      "architect": {
        // ...
      }
    }},
  // ...
}

そして、buildの下にfrdeの構成設定を作成します。

angle.json

{
  "projects": {
    "angular-internationalization-example": {
      // ...
      "architect": {
        "build": {
          // ...
          "configurations": {
            "production": {
              // ...
            },
            "fr": {
              "localize": ["fr"],
              "outputPath": "dist/under-construction-fr/",
              "i18nMissingTranslation": "error"
            },
            "de": {
              "localize": ["de"],
              "outputPath": "dist/under-construction-de/",
              "i18nMissingTranslation": "error"
            }
          }
        },
        // ...
      }
    }},
  // ...
}

注:以前は、このチュートリアルでは"i18nFile""i18nFormat"に別々の値を使用していましたが、「i18nLocale」. These have since been deprecated and localize`が推奨されるアプローチです。


serveで構成設定を更新することもできます。

angle.json

{
  "projects": {
    "angular-internationalization-example": {
      // ...
      "architect": {
        "serve": {
          // ...
          "configurations": {
            "production": {
              "browserTarget": "angular-internationalization-example:build:production"
            },
            "fr": {
              "browserTarget": "angular-internationalization-example:build:fr"
            },
            "de": {
              "browserTarget": "angular-internationalization-example:build:de"
            }
          }
        },
        // ...
      }
    }},
  // ...
}

package.json内で、新しいロケールを構築して提供する機能を含む、さらにいくつかのスクリプトを作成できるようになりました。

package.json

{
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "start:fr": "ng serve --configuration=fr",
    "start:de": "ng serve --configuration=de",
    "build": "ng build",
    "build:fr": "ng build --configuration=fr",
    "build:de": "ng build --configuration=de",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "i18n:extract": "ng xi18n --output-path src/locale"
  }
}

ターミナルで次のコマンドを実行すると、すべてのプロジェクトを開始できます。

npm start

そして、別のターミナルウィンドウで、フランス語のビルドを開始します。

npm run start:fr -- --port=4201

そして、別のターミナルウィンドウで、ドイツ語のビルドを開始します。

npm run start:de -- --port=4202

これにより、デフォルトのポートで英語、ポート4201でフランス語、ポート4202でドイツ語のアプリケーションが実行されます。

アプリケーションの翻訳バージョンを作成しました。

結論

このチュートリアルでは、Angularで利用可能な組み込みのi18nツールを使用して、フランス語とドイツ語で翻訳されたビルドを生成しました。

組み込みのi18nツールの使用方法の詳細については、公式ドキュメントを参照してください。

Angularについて詳しく知りたい場合は、Angularトピックページで演習とプログラミングプロジェクトを確認してください。