SvelteKit

載入翻譯內容

本頁說明 Intor 在 SvelteKit 專案中的翻譯內容載入方式。


在 SvelteKit 中選擇載入模式:


Bundled

在 SvelteKit 快速開始中,已示範透過 定義在設定檔中 的方式載入翻譯內容。
本節將說明另一種載入方式:依語系載入 (Dynamic Import)


依語系載入 (Dynamic Import)

沿用 SvelteKit 快速開始 的翻譯內容結構。

為了示意不同的載入方式,故暫時移除設定檔中 messages 定義,
並啟用 routing.forceFullReload,以確保語系切換時能重新載入對應的翻譯內容。

intor-config.ts
M
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.ts
U

完整實作請參考:依語系載入 (Dynamic Import)


然後,在 +layout.server.ts 中使用該載入函式載入翻譯內容。

layout.tsx
M
import { intor } from "intor/server";
import { intorConfig } from "$lib/i18n/intor-config";
import { loadMessages } from "$lib/i18n/load-messages";

export const load = async ({ locals, fetch }) => {
  const intorValue = await intor(intorConfig, locals.intor.locale, { fetch });
  const messages = await loadMessages(intorConfig, locals.intor.locale);

  return {
    intorValue: { ...intorValue, messages },
  };
};

Server-side 使用 getTranslator() 時,也必須指定相同的動態載入方式。

const { t } = await getTranslator(intorConfig, {
  locale: locals.intor.locale,
  loader: loadMessages,
});

Local Loader

關於 Local Loader,詳見:Local Loader

沿用 SvelteKit 快速開始 的翻譯內容結構。

透過 loader 設定啟用 Local Loader。

intor-config.ts
M
import { defineIntorConfig } from "intor";

export const intorConfig = defineIntorConfig({
  defaultLocale: "en",
  supportedLocales: ["en", "fr"],
  loader: { mode: "local" },
});

Remote Loader

關於 Remote Loader,詳見:Remote Loader

沿用 SvelteKit 快速開始 的翻譯內容結構。

將翻譯內容複製至 static/ 目錄,用以示意遠端服務情境。

index.json
U

index.json
U

透過 loader 設定啟用 Remote Loader。

intor-config.ts
M
import { defineIntorConfig } from "intor";

export const intorConfig = defineIntorConfig({
  defaultLocale: "en",
  supportedLocales: ["en", "fr"],
  loader: { mode: "remote", url: "http://localhost:5173/messages" },
});