Next.js
載入翻譯內容
本頁說明 Intor 在 Next.js 專案中的翻譯內容載入方式。
在 Next.js 中選擇載入模式:
- 部署於 Vercel 等託管平台時:Bundled
- 適用於需要更高彈性的情境:Local Loader 、Remote Loader
Bundled
在 Next.js 快速開始中,已示範透過 定義在設定檔中 的方式載入翻譯內容。
本節將說明另一種載入方式:依語系載入 (Dynamic Import) 。
依語系載入 (Dynamic Import)
沿用 Next.js 快速開始 的翻譯內容結構。
為了示意不同的載入方式,故暫時移除設定檔中 messages 定義,
並啟用 routing.forceFullReload,以確保語系切換時能重新載入對應的翻譯內容。
intor-config.tsM
import { defineIntorConfig } from "intor"; export const intorConfig = defineIntorConfig({ defaultLocale: "en", supportedLocales: ["en", "fr"], // messages: { en: EN, fr: FR }, routing: { forceFullReload: true }, });
接著,在 i18n/ 資料夾中建立 load-messages.ts。
load-messages.tsU
完整實作請參考:依語系載入 (Dynamic Import)
然後,在 layout.tsx 中使用該載入函式載入翻譯內容,並將結果傳入 IntorClientProvider。
layout.tsxM
// ... import { intor } from "intor/next/server"; import { intorConfig } from "@/i18n/intor-config"; import { IntorClientProvider } from "@/i18n/intor-client-provider"; import { loadMessages } from "@/i18n/load-messages"; export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { const value = await intor(intorConfig); const messages = await loadMessages(intorConfig, value.locale); return ( <html lang={value.locale}> <body> <IntorClientProvider value={{ ...value, messages }}> {children} </IntorClientProvider> </body> </html> ); }
Server-side 使用 getTranslator() 時,也必須指定相同的動態載入方式。
export const generateMetadata = async (): Promise<Metadata> => { const { t } = await getTranslator(intorConfig, { loader: loadMessages }); return { title: t("hello") }; };
Local Loader
關於 Local Loader,詳見:Local Loader
沿用 Next.js 快速開始 的翻譯內容結構。
透過 loader 設定啟用 Local Loader。
intor-config.tsM
import { defineIntorConfig } from "intor"; export const intorConfig = defineIntorConfig({ defaultLocale: "en", supportedLocales: ["en", "fr"], loader: { mode: "local" }, });
Remote Loader
關於 Remote Loader,詳見:Remote Loader
沿用 Next.js 快速開始 的翻譯內容結構。
將翻譯內容複製至 public/ 目錄,用以示意遠端服務情境。
index.jsonUindex.jsonU
透過 loader 設定啟用 Remote Loader。
intor-config.tsM
import { defineIntorConfig } from "intor"; export const intorConfig = defineIntorConfig({ defaultLocale: "en", supportedLocales: ["en", "fr"], loader: { mode: "remote", url: "http://localhost:3000/messages" }, });