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

    Intlayer を使って Vite と Svelte のウェブサイトを翻訳する | 国際化(i18n)

    目次

    Intlayerとは?

    Intlayerは、最新のウェブアプリケーションにおける多言語対応を簡素化するために設計された革新的なオープンソースの国際化(i18n)ライブラリです。

    Intlayerを使うことで、以下が可能になります:

    • コンポーネントレベルで宣言的な辞書を使い、翻訳を簡単に管理できます。
    • メタデータ、ルート、コンテンツを動的にローカライズできます。
    • 自動生成される型によりTypeScriptのサポートを確保し、オートコンプリートやエラー検出を向上させます。
    • 動的なロケール検出や切り替えなどの高度な機能を利用できます。

    ViteとSvelteアプリケーションでIntlayerをセットアップするステップバイステップガイド

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

    ステップ1: 依存関係のインストール

    npmを使って必要なパッケージをインストールします:

    npm install intlayer svelte-intlayernpm install vite-intlayer --save-dev
    • intlayer

      設定管理、翻訳、コンテンツ宣言、トランスパイル、およびCLIコマンドのための国際化ツールを提供するコアパッケージ。

    • svelte-intlayer IntlayerをSvelteアプリケーションと統合するパッケージです。Svelteの国際化のためのコンテキストプロバイダーとフックを提供します。

    • vite-intlayer IntlayerをViteバンドラーと統合するためのViteプラグイン、およびユーザーの優先ロケール検出、クッキー管理、URLリダイレクト処理のためのミドルウェアを含みます。

    ステップ2: プロジェクトの設定

    アプリケーションの言語を設定するための設定ファイルを作成します:

    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;
    この設定ファイルを通じて、ローカライズされたURL、ミドルウェアのリダイレクション、クッキー名、コンテンツ宣言の場所と拡張子、コンソールでのIntlayerログの無効化などを設定できます。利用可能なパラメータの完全なリストについては、設定ドキュメントを参照してください。

    ステップ3: Vite設定にIntlayerを統合する

    intlayerプラグインを設定に追加します。

    vite.config.ts
    import { defineConfig } from "vite";import { svelte } from "@sveltejs/vite-plugin-svelte";import { intlayer } from "vite-intlayer";// https://vitejs.dev/config/export default defineConfig({  plugins: [svelte(), intlayer()],});
    intlayer() Viteプラグインは、IntlayerをViteに統合するために使用されます。これにより、コンテンツ宣言ファイルのビルドが保証され、開発モードでの監視が行われます。また、Viteアプリケーション内でIntlayerの環境変数を定義します。さらに、パフォーマンス最適化のためのエイリアスも提供します。

    ステップ4: コンテンツの宣言

    翻訳を格納するためのコンテンツ宣言を作成および管理します。

    src/app.content.tsx
    import { t, type Dictionary } from "intlayer";const appContent = {  key: "app",  content: {    title: t({      en: "Hello World",      fr: "Bonjour le monde",      es: "Hola mundo",    }),  },} satisfies Dictionary;export default appContent;
    コンテンツ宣言は、アプリケーション内のどこにでも定義できます。contentDirディレクトリ(デフォルトは./src)に含まれていれば有効です。また、コンテンツ宣言ファイルの拡張子(デフォルトは.content.{json,ts,tsx,js,jsx,mjs,mjx,cjs,cjx})に一致する必要があります。
    詳細については、コンテンツ宣言のドキュメントを参照してください。

    ステップ5: コード内でIntlayerを利用する

    src/App.svelte
    <script>  import { useIntlayer } from "svelte-intlayer";  const content = useIntlayer("app");</script><div><!-- コンテンツをシンプルにレンダリング --><h1>{$content.title}</h1><!-- エディターを使って編集可能なコンテンツとしてレンダリング --><h1><svelte:component this={$content.title} /></h1><!-- コンテンツを文字列としてレンダリング --><div aria-label={$content.title.value}></div>

    (オプション)ステップ6: コンテンツの言語を変更する

    src/App.svelte
    <script lang="ts">import  { getLocaleName } from 'intlayer';import { useLocale } from 'svelte-intlayer';// ロケール情報と setLocale 関数を取得const { locale, availableLocales, setLocale } = useLocale();// ロケール変更を処理const changeLocale = (event: Event) => {  const target = event.target as HTMLSelectElement;  const newLocale = target.value;  setLocale(newLocale);};</script><div>  <select value={$locale} on:change={changeLocale}>    {#each availableLocales ?? [] as loc}      <option value={loc}>        {getLocaleName(loc)}      </option>    {/each}  </select></div>

    (オプション)ステップ7:Markdownのレンダリング

    Intlayerは、Markdownコンテンツを直接Svelteアプリケーション内でレンダリングすることをサポートしています。デフォルトでは、Markdownはプレーンテキストとして扱われます。MarkdownをリッチなHTMLに変換するには、@humanspeak/svelte-markdownや他のMarkdownパーサーを統合することができます。

    intlayerパッケージを使ってMarkdownコンテンツを宣言する方法については、markdownドキュメントをご覧ください。
    src/App.svelte
    <script>  import { setIntlayerMarkdown } from "svelte-intlayer";  setIntlayerMarkdown((markdown) =>   // マークダウンコンテンツを文字列としてレンダリングする   return markdown;  );</script><h1>{$content.markdownContent}</h1>
    content.markdownContent.metadata.xxx プロパティを使って、マークダウンのフロントマターのデータにもアクセスできます。

    (オプション)ステップ8: intlayerエディター / CMS のセットアップ

    intlayerエディターをセットアップするには、intlayerエディターのドキュメントに従ってください。

    intlayer CMSをセットアップするには、intlayer CMSのドキュメントに従ってください。

    並行して、Svelteアプリケーション内では、レイアウトまたはアプリケーションのルートに以下の行を追加する必要があります。

    src/layout.svelte
    import { useIntlayerEditor } from "svelte-intlayer";useIntlayerEditor();

    (オプション)ステップ7:アプリケーションにローカライズされたルーティングを追加する

    Svelteアプリケーションでローカライズされたルーティングを扱うには、svelte-spa-routerとIntlayerのlocaleFlatMapを組み合わせて、各ロケールのルートを生成できます。

    まず、svelte-spa-routerをインストールします:

    npm install svelte-spa-router

    次に、ルートを定義するために Router.svelte ファイルを作成します:

    src/Router.svelte
    <script lang="ts">import { localeFlatMap } from "intlayer";import Router from "svelte-spa-router";import { wrap } from "svelte-spa-router/wrap";import App from "./App.svelte";const routes = Object.fromEntries(    localeFlatMap(({locale, urlPrefix}) => [    [        urlPrefix || '/',        wrap({            component: App as any,            props: {                locale,            },        }),    ],    ]));</script><Router {routes} />

    main.ts を更新して、App の代わりに Router コンポーネントをマウントします:

    src/main.ts
    import { mount } from "svelte";import Router from "./Router.svelte";const app = mount(Router, {typescript fileName="src/main.ts"import { mount } from "svelte";import Router from "./Router.svelte";const app = mount(Router, {  target: document.getElementById("app")!, // アプリのマウント先のDOM要素});export default app;

    最後に、App.svelte を更新して locale プロパティを受け取り、useIntlayer と共に使用します:

    src/App.svelte
    <script lang="ts">import type { Locale } from 'intlayer';import { useIntlayer } from 'svelte-intlayer';import Counter from './lib/Counter.svelte';import LocaleSwitcher from './lib/LocaleSwitcher.svelte';export let locale: Locale; // ロケールを受け取る$: content = useIntlayer('app', locale); // ロケールに基づくコンテンツを取得</script><main>  <div class="locale-switcher-container">    <LocaleSwitcher currentLocale={locale} /> <!-- 現在のロケールを渡す -->  </div>  <!-- ... アプリの残りの部分 ... --></main>

    サーバーサイドルーティングの設定(オプション)

    並行して、intlayerProxy を使用してアプリケーションにサーバーサイドルーティングを追加することもできます。このプラグインは、URL に基づいて現在のロケールを自動的に検出し、適切なロケールクッキーを設定します。ロケールが指定されていない場合、プラグインはユーザーのブラウザの言語設定に基づいて最適なロケールを判断します。ロケールが検出されない場合は、デフォルトのロケールにリダイレクトします。

    intlayerProxy を本番環境で使用するには、vite-intlayer パッケージを devDependencies から dependencies に切り替える必要があることに注意してください。
    vite.config.ts
    import { defineConfig } from "vite";import { svelte } from "@sveltejs/vite-plugin-svelte";import { intlayer, intlayerProxy } from "vite-intlayer";typescript {3,7} fileName="vite.config.ts" codeFormat="typescript"import { defineConfig } from "vite";import { svelte } from "@sveltejs/vite-plugin-svelte";import { intlayer, intlayerProxy } from "vite-intlayer";// https://vitejs.dev/config/export default defineConfig({  plugins: [svelte(), intlayer(), intlayerProxy()],});

    (オプション)ステップ8:ロケールが変更されたときにURLを変更する

    ユーザーが言語を切り替え、URLをそれに応じて更新できるようにするために、LocaleSwitcher コンポーネントを作成できます。このコンポーネントは intlayergetLocalizedUrlsvelte-spa-routerpush を使用します。

    src/lib/LocaleSwitcher.svelte
    <script lang="ts">import { getLocaleName, getLocalizedUrl } from "intlayer";import { useLocale } from "svelte-intlayer";import { push } from "svelte-spa-router";export let currentLocale: string | undefined = undefined;// ロケール情報を取得const { locale, availableLocales } = useLocale();// ロケール変更を処理const changeLocale = (event: Event) => {  const target = event.target as HTMLSelectElement;  const newLocale = target.value;  const currentUrl = window.location.pathname;  const url = getLocalizedUrl( currentUrl, newLocale);  push(url);};</script><div class="locale-switcher">  <select value={currentLocale ?? $locale} onchange={changeLocale}>    {#each availableLocales ?? [] as loc}      <option value={loc}>        {getLocaleName(loc)}      </option>    {/each}  </select></div>

    Git 設定

    Intlayer によって生成されたファイルは無視することを推奨します。これにより、Git リポジトリへの不要なコミットを避けることができます。

    これを行うには、.gitignore ファイルに以下の指示を追加してください:

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

    VS Code 拡張機能

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

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

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

    • 翻訳キーのオートコンプリート
    • 欠落している翻訳のリアルタイムエラー検出
    • 翻訳されたコンテンツのインラインプレビュー
    • 翻訳を簡単に作成・更新できるクイックアクション

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


    さらに進む

    さらに進めるために、ビジュアルエディターを実装するか、CMSを使用してコンテンツを外部化することができます。

    Intlayerの今後のリリースに関する通知を受け取る