Paraglide JS

Paraglide JS 是 React Router v7 框架模式(基于 Vite)下的最佳 i18n 库,内置一流的 i18n 路由,支持基于 URL 的本地化。

它是一个基于编译器的 i18n 库,生成的翻译支持 tree-shaking,与基于运行时的库相比,i18n 包体积最多可缩小 70%。

  • 完全类型安全,支持 IDE 自动补全
  • 借助 i18n 路由策略,生成对 SEO 友好的本地化 URL
  • 同时支持 CSR 和 SSR

源代码

快速开始

  1. 初始化 Paraglide JS
npx @inlang/paraglide-js@latest init 
  1. 在 vite.config.ts 中添加 Vite 插件:
import { reactRouter } from "@react-router/dev/vite";
import { defineConfig } from "vite";
+import { paraglideVitePlugin } from "@inlang/paraglide-js";

export default defineConfig({
  plugins: [
    reactRouter(),
+		paraglideVitePlugin({
+			project: "./project.inlang",
+			outdir: "./app/paraglide",
+			emitTsDeclarations: true,
+		}),
  ],
});
  1. 大功告成 :)

用法

import { m } from "./paraglide/messages.js";
import { getLocale, setLocale } from "./paraglide/runtime.js";

// 使用消息
m.greeting({ name: "World" }); // "Hello World!"

// 获取和设置语言区域
getLocale();    // "en"
setLocale("de"); // 切换到德语

了解更多关于消息、参数和语言区域管理的内容 →

使用中间件进行服务端渲染

在 react-router.config.ts 中启用 middleware 标志:

export default {
  ssr: true,
  future: {
    v8_middleware: true,
  },
} satisfies Config;

直接在 root.tsx 中内联定义中间件:

import { type MiddlewareFunction } from "react-router";
import { paraglideMiddleware } from "./paraglide/server.js";

export const middleware: MiddlewareFunction[] = [
  (ctx, next) => paraglideMiddleware(ctx.request, () => next()),
];

在 routes.ts 中:

import {
  type RouteConfig,
  index,
  prefix,
  route,
} from "@react-router/dev/routes";

export default [
  // 为每个路径添加可选的 :locale 前缀
  // 设为可选,这样既能匹配不带语言区域的路径 `/page`
  // 也能匹配带语言区域的路径 `/en/page`
  //
  // * 如果你使用 `url` 策略,
  // * 请确保此处定义的模式与
  // * Paraglide JS 的 urlPatterns 一致
  //
  // React Router 中间件目前还不支持将重写后的
  // Request 传递给 loader,因此请在这里保留语言区域前缀。
+	...prefix(":locale?", [
    index("routes/home.tsx"),
    route("about", "routes/about.tsx"),
+	]),
] satisfies RouteConfig;

现在你可以在项目中的任意位置使用 getLocale 函数了。

翻译后的路径名

React Router 会将传入的 URL 与你在 routes.ts 中定义的路由进行匹配。中间件可以设置语言区域和请求上下文,但 React Router 的中间件 API 不允许 Paraglide 在路由匹配之前将重写后的请求传给 next()。

如果你使用翻译后的路径名,请在 routes.ts 中定义本地化的路由别名,并将它们指向同一个路由模块。如果多个条目使用同一个文件,请为每个别名指定唯一的路由 id。

import { type RouteConfig, index, route } from "@react-router/dev/routes";

export default [
  index("routes/home.tsx"),
  route("en/pricing", "routes/pricing.tsx", { id: "pricing-en" }),
  route("de/preise", "routes/pricing.tsx", { id: "pricing-de" }),
  route("pl/cennik", "routes/pricing.tsx", { id: "pricing-pl" }),
] satisfies RouteConfig;

保留对应的 Paraglide urlPatterns,这样 localizeHref("/pricing") 等辅助函数生成的公开 URL 才能被 React Router 匹配:

paraglideVitePlugin({
  project: "./project.inlang",
  outdir: "./app/paraglide",
  emitTsDeclarations: true,
  strategy: ["url", "baseLocale"],
  urlPatterns: [
    {
      pattern: "/pricing",
      localized: [
        ["en", "/en/pricing"],
        ["de", "/de/preise"],
        ["pl", "/pl/cennik"],
      ],
    },
  ],
});

不使用中间件的服务端渲染 (旧版)

如果暂时还无法使用中间件,也可以手动接入 SSR:

在 root.tsx 中:

import {
  assertIsLocale,
  baseLocale,
  getLocale,
  isLocale,
  overwriteGetLocale,
} from "./paraglide/runtime";

+export function loader(args: Route.LoaderArgs) {
+	return {
    // 从路径中检测语言区域。如果未找到语言区域,则使用 baseLocale。
    // 例如,/de 会将语言区域设置为 "de"
+		locale: isLocale(args.params.locale) ? args.params.locale : baseLocale,
+	};
}

// 服务端渲染需要按请求隔离作用域
// 通过 react context 将语言区域限定在每个请求内
// 并重写 getLocale(),使其从 react context 中读取
+const LocaleContextSSR = createContext(baseLocale);
+if (import.meta.env.SSR) {
+	overwriteGetLocale(() => assertIsLocale(useContext(LocaleContextSSR)));
+}

export default function App(props: Route.ComponentProps) {
  return (
    // 使用语言区域
+		<LocaleContextSSR.Provider value={props.loaderData.locale}>
      <Outlet />
+		</LocaleContextSSR.Provider>
  );
}

先推导出 loader 的返回类型,以便与 meta 函数共用:

type RootLoaderData = Awaited<ReturnType<typeof loader>>;

Meta 标签生成

React Router 会在客户端的独立上下文中生成 <meta> 标签。为了 确保 getLocale 辅助函数在生成过程中返回正确的语言区域, 请按如下方式更新你的 meta 函数:

export function meta({ data }: Route.MetaArgs) {
  if (!import.meta.env.SSR) {
    const locale = assertIsLocale(
      (data as RootLoaderData | undefined)?.locale ?? baseLocale,
    );

    overwriteGetLocale(() => locale);
  } else {
    overwriteGetLocale(() =>
      assertIsLocale(useContext<Locale>(LocaleContextSSR))
    );
  }

  return [];
}

这与上文的服务端设置相同,同时能确保即使并行处理多个请求,meta 生成步骤也始终使用正确的语言区域。请通过 data (即 loaderData) 参数获取根 loader 返回的语言区域,而不是通过 matches 获取。

在 routes.ts 中:

import {
  type RouteConfig,
  index,
  prefix,
  route,
} from "@react-router/dev/routes";

export default [
  // 为每个路径添加可选的 :locale 前缀
  // 设为可选,既能匹配不带语言区域的路径 `/page`
  // 也能匹配带语言区域的路径 `/en/page`
  //
  // * 如果使用 `url` 策略,请确保此处定义的模式
  // * 与 paraglide JS 的 urlPatterns 相匹配
  // *
+	...prefix(":locale?", [
    index("routes/home.tsx"),
    route("about", "routes/about.tsx"),
+	]),
] satisfies RouteConfig;