載入翻譯內容

翻譯內容的載入方式在 Intor 中被明確區分,以因應不同的應用型態與部署需求。


載入方式主要分為兩種類型:

  • Bundled :在建置階段被打包進應用程式。
  • Loader :於執行階段載入,適用於更具彈性的場景。

Bundled

翻譯內容在建置階段被打包進應用程式中。

包含直接定義與依語系載入兩種方式。

此方式適合部署於各種託管平台(如 Vercel)與純前端專案。


定義在設定檔中 (Static Import)

直接在設定檔中定義翻譯內容,適合翻譯內容固定且規模較小的情境。

import { defineIntorConfig } from "intor";
import EN from "../../messages/en/index.json";
import FR from "../../messages/fr/index.json";

export const intorConfig = defineIntorConfig({
  defaultLocale: "en",
  supportedLocales: ["en", "fr"],
  messages: {
    en: EN,
    fr: FR,
  },
});

依語系載入 (Dynamic Import)

當翻譯內容規模較大,或需依語系拆分檔案時,可透過 import() 依語系載入對應的翻譯內容。

此方式需提供一個翻譯內容載入函式 loadMessages,以下為基本實作方式:

import type { IntorResolvedConfig, LocaleMessages } from "intor";
import { mergeMessages } from "intor";

export async function loadMessages(
  config: IntorResolvedConfig,
  locale: string,
): Promise<LocaleMessages> {
  // Adjust the import path based on your project structure.
  const loaded: LocaleMessages = {
    [locale]: (await import(`../../messages/${locale}/index.json`)).default,
  };
  return mergeMessages(config.messages, loaded, { config, locale });
}

整合方式依各執行環境而定,詳見:框架指南

在具備 server-side routing 的框架中,需啟用 routing.forceFullReload


Loader

翻譯內容於執行階段載入。
適用於需要更高彈性的應用情境。


比較

面向BundledLoader
載入時機建置階段執行階段
是否包含於前端 bundle
是否需要伺服器執行環境
是否支援外部來源(CDN、DB)
更新翻譯內容需重新部署不需重新部署
部署複雜度較低較高