为 TanStack Start 应用添加翻译

解析带语言区域前缀的请求,加载对应目录,并渲染带有规范 URL 和语言切换器的翻译页面。

让 /about 等应用路由独立于语言,同时让读者通过 /en/about 或 /de/about 访问页面。@lingo.dev/react-tanstack 将这一 URL 策略与请求上下文和目录关联起来。路由仍匹配 /about;请求的语言区域决定使用哪些消息,以及由此生成的 URL。

本指南为现有的 TanStack Start 应用添加英语和德语支持,使用 React 19、TanStack Router 1.170+ 和 Start 1.168+。Start 被声明为可选的对等依赖,但软件包的根模块会导入 Start 的 createIsomorphicFn。即使纯 Router 应用已显式提供 URL,也需要在安装适配器时一并安装 Start。

定义语言区域策略和目录 #

安装软件包:

sh
npm install @lingo.dev/react@1.17.1 @lingo.dev/react-tanstack@1.17.1 @lingo.dev/locale-router@0.2.1
npm install @lingo.dev/spec@1.17.1 jsonc-parser
npm install --save-dev @lingo.dev/cli@latest

将目录加载中的 loadMatchedMessages 函数添加为 src/catalog.ts。然后创建 src/i18n.ts:

ts
import { createLocaleRouter } from "@lingo.dev/locale-router";
import type { Catalog } from "@lingo.dev/react-tanstack";
import source from "../locales/en.jsonc?raw";
import { loadMatchedMessages } from "./catalog";

export const locales = createLocaleRouter(["en", "de"] as const, {
  defaultLocale: "en",
  exclude: ["api", "assets"],
});

const targets = import.meta.glob<string>("../locales/*.jsonc", {
  query: "?raw",
  import: "default",
});

export const catalog: Catalog = async (locale) => {
  const load = targets[`../locales/${locale}.jsonc`];
  if (!load) throw new Error(`Missing catalog for ${locale}`);
  return loadMatchedMessages(source, await load());
};

这个 Vite 加载器会验证原始文件,并从对应的英语源文件中选取有效键,避免不含注释的翻译输出重新启用孤立条目。文件缺失或格式有误时,它会报错,而不是静默返回空映射。下方的提取步骤会在应用启动前创建需要导入的源文件。

创建路由器前先解析请求 #

在 src/start.ts 中注册无前缀路径中间件,同时保留所有现有中间件:

ts
import { createStart } from "@tanstack/react-start";
import { localeMiddleware } from "@lingo.dev/react-tanstack/server";
import { locales } from "./i18n";

export const startInstance = createStart(() => ({
  requestMiddleware: [localeMiddleware(locales)],
}));

在 src/router.tsx 中,将解析出的语言区域和消息用作路由器上下文:

tsx
import { createRouter } from "@tanstack/react-router";
import { lingoContext, localeRewrite } from "@lingo.dev/react-tanstack";
import { routeTree } from "./routeTree.gen";
import { catalog, locales } from "./i18n";

export async function getRouter() {
  const state = await lingoContext(locales, catalog);
  return createRouter({
    routeTree,
    context: state,
    rewrite: localeRewrite(locales, state.locale),
  });
}

declare module "@tanstack/react-router" {
  interface Register {
    router: Awaited<ReturnType<typeof getRouter>>;
  }
}

保留应用的其他路由器设置。lingoContext 使用识别出的 URL 前缀;若未识别到前缀,则使用默认语言区域。它在服务器上读取请求 URL,在浏览器中读取 location.href;也可以通过可选的第三个参数 URL 显式指定输入。它本身不执行 Accept-Language 协商,而是由中间件对符合条件的无前缀路径请求执行协商,并返回 302 重定向。

localeRewrite 会移除识别出的前缀以匹配路由,并为符合条件的出站路径添加请求的语言区域前缀。路由定义应保持不带前缀,并按上文所述将 API 和资源路径排除在本地化范围之外。

根据请求上下文渲染根组件 #

在 src/routes/__root.tsx 中,保留框架外壳,同时加入上下文提供器:

tsx
import { createRootRouteWithContext, HeadContent, Outlet, Scripts } from "@tanstack/react-router";
import { createLingo, LingoProvider, type Messages } from "@lingo.dev/react";

type LocaleContext = { locale: "en" | "de"; messages: Messages };

export const Route = createRootRouteWithContext<LocaleContext>()({
  component: Outlet,
  shellComponent: ({ children }) => {
    const { locale, messages } = Route.useRouteContext();
    return (
      <html lang={locale} dir={createLingo(locale).direction}>
        <head>
          <HeadContent />
        </head>
        <body>
          <LingoProvider locale={locale} messages={messages}>
            {children}
          </LingoProvider>
          <Scripts />
        </body>
      </html>
    );
  },
});

现在,文本、格式设置和文档属性都由同一上下文驱动。水合时应保留该上下文;如果将消息替换为空的客户端映射,渲染出的页面就会发生变化。

添加翻译页面和头部元数据 #

创建 src/routes/about.tsx:

tsx
import { createFileRoute } from "@tanstack/react-router";
import { useLingo } from "@lingo.dev/react";
import { getLingo, lingoHead } from "@lingo.dev/react-tanstack";
import { locales } from "../i18n";

export const Route = createFileRoute("/about")({
  head: (options) => {
    const l = getLingo(options);
    const localized = lingoHead({
      router: locales,
      locale: options.match.context.locale,
      pathname: options.match.pathname,
      origin: "https://example.com",
    });
    return {
      meta: [{ title: l.text("About us", { context: "About page title" }) }, ...localized.meta],
      links: localized.links,
    };
  },
  component: About,
});

function About() {
  const l = useLingo();
  return <h1>{l.text("About us", { context: "About page heading" })}</h1>;
}

将示例源地址替换为你信任的站点源地址。在 head 中,先绑定 const l = getLingo(options),再进行需要提取的调用;链式 getLingo(options).text(...) 不是受支持的提取模式。

头部元数据 #

lingoHead 返回 { meta, links }:各语言区域的规范链接和替代链接,以及 x-default 和 og:url/og:locale。请提供不带前缀、查询参数或哈希片段的路径名。对于德语 /about,规范 URL 为 https://example.com/de/about;在此策略下,默认英语替代 URL 为 /en/about。

该辅助函数会移除非根路径末尾的一个斜杠。Open Graph 语言区域由补全后的语言和地区信息推导而来,例如 de_DE;可选的 ogLocale 覆盖设置可用于处理特定平台的写法。LingoHead 是结果类型,而不是 Next 适配器的 JSX 组件。

提取并获取目录 #

运行 npx lingo extract --src src --source-locale en。如果是新配置,请以 de 为目标初始化 locales/en.jsonc,完成身份验证,关联本地化引擎,然后获取第一个目标:

sh
npx lingo init --source en --targets de --files 'locales/en.jsonc' --yes
npx lingo login
npx lingo link
npx lingo push --backfill-missing --wait

如果已有配置,请保留其绑定和高级设置。提取后,先完成现有目标的常规更新,获取并检查这些目标,再添加 de 并补齐内容,同时保持源版本不变。这种情况下,请遵循目录加载和添加语言流程。确保 locales/en.jsonc 和所需的 locales/de.jsonc 都已存在后,再启动应用。访问 /en/about 和 /de/about,检查页面标题和文档标题,并核对其规范 URL 和替代 URL。

通过完整请求切换语言 #

tsx
import { useLocaleSwitch } from "@lingo.dev/react-tanstack";
import { locales } from "./i18n";

export function Languages() {
  const options = useLocaleSwitch(locales);
  return (
    <nav aria-label="Language">
      {options.map((option) => (
        <a key={option.locale} href={option.href} aria-current={option.current ? "page" : undefined}>
          {option.label}
        </a>
      ))}
    </nav>
  );
}

将此组件放在 src 下,并在路由应用内渲染。每个选项包含 locale、以该语言自身书写的名称 label、href 和 current。普通锚点链接会发起新请求,加载对应语言区域的目录。仅在客户端跳转的路由链接可能仍会保留旧请求的消息。切换器会保留查询参数和哈希片段,并将 x-default 排除在可选语言之外。

内置目录和服务器辅助函数 #

createCatalog(import.meta.glob("../locales/*.jsonc", { query: "?raw" }), { sourceLocale: "en" }) 为元数据可直接使用的文件提供带缓存的 Catalog。这些模块必须解析为包含字符串类型 default 导出的对象。它会过滤文件中的孤立条目,为每个语言区域缓存一个 Promise,并在模块缺失、加载失败或解析出错时返回 {}。设置 sourceLocale 后,它会在生产环境中跳过该语言区域的文件,回退到源内容。它不会验证值为字符串的扁平结构、按路由过滤或恢复丢失的元数据;对于翻译后的 JSONC,上文将源内容与译文合并的加载器可满足这些需求。

服务器入口导出 localeMiddleware 和 canonicalSearch。中间件会保留查询参数,但会按 TanStack 的默认方式重新序列化;服务器请求不包含浏览器哈希片段。已带前缀、被排除或符合单独规范化条件的路径会继续交给 next() 处理。有关前缀和规范化的确切行为,请参阅 locale-router。

纯 TanStack Router 应用可以向 lingoContext 提供 URL,自行实现重定向,同时保留根软件包对 Start 的依赖。本指南中的中间件和请求外壳专门适用于 Start。