快速開始
Express
本頁示範 Intor 在 Express 專案中的最小整合流程。
安裝
本頁假設 Express 專案環境已就緒。
相關設定請參考:Express
安裝 Intor:
npm install intoryarn add intorpnpm add intorbun add intor
專案結構
index.jsonUindex.jsonUindex.tsUintor-config.tsU
整合步驟
♯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/ 下建立 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 初始化
在 src/ 下建立 index.ts。
初始化 Express 應用程式,並註冊 Intor 的 request handler。
index.tsU
import express from "express"; import { createIntorHandler } from "intor/express"; import { intorConfig } from "./intor-config"; const app = express(); app.use(createIntorHandler(intorConfig)); app.listen(3000, () => { console.log(`Server is running on http://localhost:3000`); });
使用範例
透過 getTranslator 取得翻譯相關能力:
t:取得對應文字tRich:渲染包含語意 tag 的結構化翻譯內容
index.tsM
import { getTranslator } from "intor/express"; // ... app.get("/", async function (req, res) { const { t, tRich } = await getTranslator(intorConfig, req); res.send({ hello: t("hello", { name: "Intor" }), rich: tRich("rich", { tag: (children) => `<b>${children}</b>` }), }); }); // ...
作為便利方式,翻譯能力亦可直接自
req取得,但此方式下型別推導能力有限。app.get("/", async function (req, res) { res.send({ hello: req.t("hello", { name: "Intor" }), rich: req.tRich("rich", { tag: (children) => `<b>${children}</b>` }), }); });