快速開始
React
本頁示範 Intor 在 React 專案中的最小整合流程。
安裝
在此範例中,我們使用 Vite 來建立 React 專案,詳見:Vite
安裝 Intor:
npm install intoryarn add intorpnpm add intorbun add intor
專案結構
index.jsonUindex.jsonUApp.tsxMmain.tsxMintor-config.tsUintor-client-provider.tsxU
整合步驟
♯1 翻譯內容
在專案中建立 messages 資料夾,並依語系建立子資料夾,每個語系提供一個 index.json。
index.jsonUindex.jsonU
{ "hello": "Hello, {name}", "rich": "A <tag>text</tag>." }
{ "hello": "Bonjour, {name}", "rich": "Un <tag>texte</tag>." }
♯2 設定檔
在 src/ 下建立 i18n/ 資料夾,並於其中建立 intor-config.ts。
本範例採用最基本的翻譯內容載入方式,直接將 messages 定義於設定檔中。
詳見:載入翻譯內容
intor-config.tsU
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, }, });
♯3 初始化
在 i18n/ 資料夾中建立 intor-client-provider.tsx。
intor-client-provider.tsxU
import type { ReactNode } from "react"; import { getClientLocale } from "intor"; import { IntorProvider } from "intor/react"; import { intorConfig } from "./intor-config"; export function IntorClientProvider({ children }: { children: ReactNode }) { const locale = getClientLocale(intorConfig); return ( <IntorProvider value={{ config: intorConfig, locale }}> {children} </IntorProvider> ); }
接著,在 main.tsx 中使用這個 provider 包裹整個應用程式。
main.tsxM
// ... import { IntorClientProvider } from "./i18n/intor-client-provider.tsx"; createRoot(document.getElementById("root")!).render( <StrictMode> <IntorClientProvider> <App /> </IntorClientProvider> </StrictMode>, );
使用範例
透過 useTranslator 取得翻譯相關能力:
t:取得對應文字tRich:渲染包含語意 tag 的結構化翻譯內容setLocale:切換當前語系
App.tsxM
// ... import { useTranslator } from "intor/react"; function App() { const { t, tRich, setLocale } = useTranslator(); return ( <> <p>{t("hello", { name: "Intor" })}</p> <p>{tRich("rich", { tag: (children) => <b>{children}</b> })}</p> <button onClick={() => setLocale("en")}>English</button> <button onClick={() => setLocale("fr")}>French</button> </> ); } export default App;