このページとあなたの好きなAIアシスタントを使ってドキュメントを要約します
バージョン履歴
- "Solid の useIntlayer API の使用法を直接プロパティアクセスに更新"v8.9.02026/5/4
- "Astro + Vanilla JSの初期ドキュメント"v8.7.72026/4/24
このページのコンテンツはAIを使用して翻訳されました。
英語の元のコンテンツの最新バージョンを見るIf you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy doc Markdown to clipboard
Intlayerを使用したAstro + Vanilla JSサイトの翻訳 | 国際化 (i18n)
目次
代替手段ではなく Interlayer を使用する理由
「astro-i18n」や「i18next」などの主要なソリューションと比較して、Intlayer は次のような統合された最適化を備えたソリューションです。
Astro を完全にカバー
Intlayer は、多言語ルーティング、サイトマップ、および国際化 (i18n) の拡張に必要なすべての機能を提供することで、Astro と完全に連携するように最適化されています。
バンドルサイズ
大量の JSON ファイルをページにロードするのではなく、必要なコンテンツのみをロードします。 Intlayer は、バンドルとページのサイズを最大 50% 削減するのに役立ちます。
保守性
アプリケーションのコンテンツのスコープを設定すると、大規模なアプリケーションの メンテナンスが容易になります。コンテンツ コードベース全体を確認するという精神的な負担を負うことなく、単一の機能フォルダーを複製または削除できます。さらに、Intlayer は完全に型指定されており、コンテンツの正確性を保証します。
AI エージェント
コンテンツを同じ場所に配置すると、大規模言語モデル (LLM) によって 必要なコンテキストが削減されます。 Intlayer には、翻訳の欠落をテストする CLI、LSP、MCP などのツール スイートも付属しています。および エージェント スキル により、AI エージェントの開発者エクスペリエンス (DX) がさらにスムーズになります。
オートメーション
AI プロバイダーの費用で、選択した LLM を使用して CI/CD パイプラインで自動化を変換します。 Intlayer は、コンテンツ抽出を自動化する コンパイラー と、バックグラウンドでの翻訳を支援する Web プラットフォーム も提供します。
パフォーマンス
大量の JSON ファイルをコンポーネントに接続すると、パフォーマンスと反応性の問題が発生する可能性があります。 Intlayer は、ビルド時のコンテンツの読み込みを最適化します。
非開発によるスケーリング
Intlayer は単なる i18n ソリューションではなく、自己ホスト型 ビジュアル エディター と 完全な CMS を提供します。 リアルタイムで多言語コンテンツを管理できるようになり、翻訳者、コピーライター、その他のチーム メンバーとのコラボレーションがシームレスになります。コンテンツはローカルおよび/またはリモートに保存できます。
Astro + Vanilla JSへのIntlayer設定ステップバイステップガイド
GitHubでアプリケーションテンプレートを表示。
依存関係のインストール
お好みのパッケージマネージャーを使用して、必要なパッケージをインストールします:
bashコードをコピーコードをクリップボードにコピー
npm install intlayer astro-intlayer vanilla-intlayernpx intlayer initintlayer 設定管理、翻訳、コンテンツ宣言、トランスパイル、およびCLIコマンドのための国際化ツールを提供するコアパッケージ。
astro-intlayer IntlayerをViteバンドラーと統合するためのAstro統合プラグイン、およびユーザーの優先ロケールの検出、クッキーの管理、URLリダイレクトの処理を行うミドルウェアが含まれています。
vanilla-intlayer IntlayerをVanilla JavaScript / TypeScriptアプリケーションと統合するパッケージ。UIフレームワークを使用せずに、Astroの
<script>タグの任意の部分が言語変更に応答できるように、pub/subシングルトン (IntlayerClient) とコールバックベースのヘルパー (useIntlayer、useLocaleなど) を提供します。
プロジェクトの設定
アプリケーションの言語を設定するための設定ファイルを作成します:
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ログの無効化などを設定できます。利用可能なパラメータの全リストについては、設定ドキュメントを参照してください。
Astro設定へのIntlayerの統合
Astroの設定にintlayerプラグインを追加します。Vanilla JSの場合、追加のUIフレームワーク統合は必要ありません。
astro.config.tsコードをコピーコードをクリップボードにコピー
// @ts-checkimport { intlayer } from "astro-intlayer";import { defineConfig } from "astro/config";// https://astro.build/configexport default defineConfig({ integrations: [intlayer()],});Astro統合プラグイン
intlayer()は、IntlayerをAstroと統合するために使用されます。コンテンツ宣言ファイルの構築を確実にし、開発モードで監視します。Astroアプリケーション内でIntlayerの環境変数を定義し、パフォーマンス最適化のためのエイリアスを提供します。コンテンツの宣言
翻訳を保存するためのコンテンツ宣言を作成・管理します:
src/app.content.tsコードをコピーコードをクリップボードにコピー
import { t, type Dictionary } from "intlayer";const appContent = { key: "app", content: { greeting: t({ en: "Hello World", fr: "Bonjour le monde", es: "Hola mundo", ja: "こんにちは世界", }), description: t({ en: "Welcome to my multilingual Astro site.", fr: "Bienvenue sur mon site Astro multilingue.", es: "Bienvenido a mi sitio Astro multilingüe.", ja: "多言語対応のAstroサイトへようこそ。", }), switchLocale: t({ en: "Switch language:", fr: "Changer de langue :", es: "Cambiar idioma:", ja: "言語を切り替える:", }), },} satisfies Dictionary;export default appContent;コンテンツ宣言は、
contentDir(デフォルトは./src)に含まれ、コンテンツ宣言ファイルの拡張子(デフォルトは.content.{json,ts,tsx,js,jsx,mjs,cjs})と一致していれば、アプリケーション内のどこにでも定義できます。詳細については、コンテンツ宣言のドキュメントを参照してください。
Astroでのコンテンツの使用
Vanilla JSの場合、初期のサーバーサイドレンダリングには
.astroファイル内でgetIntlayerを使用してすべてのレンダリングが行われます。その後、<script>ブロックがクライアントサイドでvanilla-intlayerを初期化し、言語の切り替えを処理します。src/pages/[...locale]/index.astroコードをコピーコードをクリップボードにコピー
---import { getIntlayer, getLocaleFromPath, getLocalizedUrl, getPrefix, getLocaleName, localeMap, locales, defaultLocale, getPathWithoutLocale, type LocalesValues,} from "intlayer";export const getStaticPaths = () => { return localeMap(({ locale }) => ({ params: { locale: getPrefix(locale).localePrefix }, }));};const locale = getLocaleFromPath(Astro.url.pathname) as LocalesValues;const pathWithoutLocale = getPathWithoutLocale(Astro.url.pathname);const { greeting, description, switchLocale } = getIntlayer("app", locale);---<!doctype html><html lang={locale} dir={getHTMLTextDir(locale)}> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <title>{greeting}</title> <!-- 正規リンク --> <link rel="canonical" href={new URL(getLocalizedUrl(Astro.url.pathname, locale), Astro.site)} /> <!-- Hreflangリンク --> { localeMap(({ locale: mapLocale }) => ( <link rel="alternate" hreflang={mapLocale} href={new URL( getLocalizedUrl(Astro.url.pathname, mapLocale), Astro.site )} /> )) } <link rel="alternate" hreflang="x-default" href={new URL( getLocalizedUrl(Astro.url.pathname, defaultLocale), Astro.site )} /> </head> <body> <main> <h1 id="greeting">{greeting}</h1> <p id="description">{description}</p> <div class="locale-switcher"> <span class="switcher-label">{switchLocale}</span> <div class="locale-buttons"> { locales.map((localeItem) => ( <a href={localeItem === locale ? undefined : getLocalizedUrl(pathWithoutLocale, localeItem)} class={`locale-btn ${localeItem === locale ? "active" : ""}`} data-locale={localeItem} aria-disabled={localeItem === locale} > {getLocaleName(localeItem)} </a> )) } </div> </div> </main> </body></html>alt、title、href、aria-labelなどの文字列属性でコンテンツを使用したい場合は、次のように関数の値を使用できます。htmlコードをコピーコードをクリップボードにコピー
<img src="{content.image.src.value}" alt="{content.image.value}" /><img src="{content.image.src.toString()}" alt="{content.image.toString()}" /><img src="{String(content.image.src)}" alt="{String(content.image)}" />ルーティング設定に関する注意: 使用するディレクトリ構造は、
intlayer.config.tsのmiddleware.routing設定によります:prefix-no-default(デフォルト): ルート(プレフィックスなし)にデフォルト言語を保持し、他の言語にはプレフィックスを付けます。すべてのケースをキャッチするために[...locale]を使用します。prefix-all: すべてのURLに言語プレフィックスが付きます。ルートを個別に処理する必要がない場合は、標準の[locale]を使用できます。search-paramまたはno-prefix: ロケールフォルダは不要です。ロケールは検索パラメータまたはクッキーを通じて処理されます。
言語切り替え機能の追加
AstroでのVanilla JSの場合、言語切り替えは通常のリンクとしてサーバーサイドでレンダリングされ、クライアントサイドで
<script>ブロックを通じてハイドレーションされます。ユーザーが言語リンクをクリックすると、vanilla-intlayerがローカライズされたURLに移動する前にsetLocaleを通じて言語クッキーを設定します。src/pages/[...locale]/index.astroコードをコピーコードをクリップボードにコピー
<!-- サーバーサイドのマークアップは上記のステップ5を参照 --><script> import { installIntlayer, useLocale } from "vanilla-intlayer"; import { getLocaleFromPath, getLocalizedUrl, type LocalesValues } from "intlayer"; // 現在のURLからロケールを使用してクライアントサイドのIntlayerを初期化 const locale = getLocaleFromPath(window.location.pathname); installIntlayer({ locale: locale as LocalesValues }); const { setLocale } = useLocale({ onLocaleChange: (newLocale: LocalesValues) => { window.location.href = getLocalizedUrl(window.location.pathname, newLocale); }, }); // 言語切り替えリンクにクリックイベントをアタッチ const localeLinks = document.querySelectorAll("[data-locale]"); localeLinks.forEach((link) => { link.addEventListener("click", (e) => { const localeValue = link.getAttribute("data-locale") as LocalesValues; if (localeValue && localeValue !== locale) { e.preventDefault(); setLocale(localeValue); } }); });</script>固定の維持に関する注意:
installIntlayerは、サーバーによって定義されたロケールでIntlayerシングルトンを初期化します。onLocaleChangeを伴うuseLocaleは、移動前にミドルウェアを介して言語クッキーを設定し、将来の訪問時にユーザーの好みが記憶されるようにします。プログレッシブエンハンスメントに関する注意: 言語切り替えリンクは、JavaScriptがなくても標準の
<a>タグとして機能します。JSが利用可能な場合、setLocaleの呼び出しが移動前にクッキーを更新するため、ミドルウェアが正しいリダイレクトを実行できます。サイトマップとRobots.txt
Intlayerは、動的にローカライズされたサイトマップとrobots.txtファイルを生成するためのユーティリティを提供します。
サイトマップ
Intlayer には、アプリケーションのサイトマップを簡単に作成できるサイトマップ ジェネレーターが組み込まれています。ローカライズされたルートを処理し、検索エンジンに必要なメタデータを追加します。
Intlayer によって生成されたサイトマップは、
xhtml:link名前空間 (Hreflang XML Extensions) をサポートしています。生の URL のみを表示するデフォルトのサイトマップ ジェネレーターとは異なり、Intlayer はページのすべての言語バージョン (例:/about、/about?lang=fr、/about?lang=es) 間に必要な双方向リンクを自動的に作成します。これにより、検索エンジンが正しい言語バージョンを正しい対象者に正しくインデックス付けして提供できるようになります。すべてのローカライズされたルートを含むサイトマップを生成するために、
src/pages/sitemap.xml.tsを作成します。src/pages/sitemap.xml.tsコードをコピーコードをクリップボードにコピー
import type { APIRoute } from "astro";import { generateSitemap, type SitemapUrlEntry } from "intlayer";const pathList: SitemapUrlEntry[] = [ { path: "/", changefreq: "daily", priority: 1.0 }, { path: "/about", changefreq: "monthly", priority: 0.7 },];const SITE_URL = import.meta.env.SITE ?? "http://localhost:4321";export const GET: APIRoute = async ({ site }) => { const xmlOutput = generateSitemap(pathList, { siteUrl: SITE_URL }); return new Response(xmlOutput, { headers: { "Content-Type": "application/xml" }, });};Robots.txt
検索エンジンのクロールを制御するために
src/pages/robots.txt.tsを作成します。src/pages/robots.txt.tsコードをコピーコードをクリップボードにコピー
import type { APIRoute } from "astro";import { getMultilingualUrls } from "intlayer";const getAllMultilingualUrls = (urls: string[]) => urls.flatMap((url) => Object.values(getMultilingualUrls(url)) as string[]);const disallowedPaths = getAllMultilingualUrls(["/admin", "/private"]);export const GET: APIRoute = ({ site }) => { const robotsTxt = [ "User-agent: *", "Allow: /", ...disallowedPaths.map((path) => `Disallow: ${path}`), "", `Sitemap: ${new URL("/sitemap.xml", site).href}`, ].join("\n"); return new Response(robotsTxt, { headers: { "Content-Type": "text/plain" }, });};Extract the content of your components
オプションIf you have an existing codebase, transforming thousands of files can be time-consuming.
To ease this process, Intlayer propose a compiler / extractor to transform your components and extract the content.
To set it up, you can add a
compilersection in yourintlayer.config.tsfile:intlayer.config.tsコードをコピーコードをクリップボードにコピー
import { type IntlayerConfig } from "intlayer"; const config: IntlayerConfig = { // ... Rest of your config compiler: { /** * Indicates if the compiler should be enabled. */ enabled: true, /** * Defines the output files path */ output: ({ fileName, extension }) => `./${fileName}${extension}`, /** * Indicates if the components should be saved after being transformed. * * - If `true`, the compiler will rewrite the component file in the disk. So the transformation will be permanent, and the compiler will skip the transformation for the next process. That way, the compiler can transform the app, and then it can be removed. * * - If `false`, the compiler will inject the `useIntlayer()` function call into the code in the build output only, and keep the base codebase intact. The transformation will be done only in memory. */ saveComponents: false, /** * Dictionary key prefix */ dictionaryKeyPrefix: "", }, }; export default config;Run the extractor to transform your components and extract the content
bashコードをコピーコードをクリップボードにコピー
npx intlayer extract
TypeScriptの設定
Intlayerはモジュール拡張を使用してTypeScriptの利点を活かし、コードベースをより堅牢にします。


TypeScriptの設定に自動生成された型が含まれていることを確認してください。
コードをクリップボードにコピー
{ // ... 既存のTypeScript設定 include: [ // ... 既存のTypeScript設定 ".intlayer/**/*.ts", // 自動生成された型を含める ],}Gitの設定
Intlayerによって生成されたファイルを無視することをお勧めします。これにより、それらをGitリポジトリにコミットすることを避けることができます。
そのためには、.gitignoreファイルに以下の指示を追加してください:
コードをクリップボードにコピー
# Intlayerによって生成されたファイルを無視.intlayerVS Code拡張機能
Intlayerを使用した開発体験を向上させるために、公式のIntlayer VS Code拡張機能をインストールできます。
この拡張機能は以下を提供します:
- 翻訳キーのオートコンプリート。
- 欠落している翻訳のリアルタイムエラー検出。
- 翻訳されたコンテンツのインラインプレビュー。
- 翻訳を簡単に作成・更新するためのクイックアクション。
拡張機能の使用方法の詳細については、Intlayer VS Code拡張機能のドキュメントを参照してください。
さらに詳しく
さらに詳しく知りたい場合は、ビジュアルエディターを実装したり、CMSを使用してコンテンツを外部化したりすることもできます。