作者:
    Creation:2025-09-04Last update:2026-06-23

    使用Intlayer翻译您的React Router v7 | 国际化(i18n)

    本指南演示了如何在 React Router v7 项目中集成 Intlayer,实现无缝国际化,支持基于区域的路由、TypeScript 支持以及现代开发实践。

    对于客户端路由,请参阅 Intlayer 与 React Router v7 指南。

    目录

    为什么选择 Inlayer 而不是替代品?

    与“react-i18next”或“i18next”等主要解决方案相比,Intlayer是一个具有集成优化的解决方案,例如:

    完整的 React Router 覆盖

    Intlayer 经过优化,可与 React Router 完美配合,提供区域设置感知路由用于区域设置检测的中间件以及扩展国际化 (i18n) 所需的所有功能。

    捆绑尺寸

    不要将大量 JSON 文件加载到页面中,而只需加载必要的内容。 Intlayer 有助于将捆绑包和页面大小减少多达 50%

    可维护性

    确定应用程序内容的范围有利于大型应用程序的维护。您可以复制或删除单个功能文件夹,而无需承担检查整个内容代码库的精神负担。此外,Intlayer 具有完全类型化 (fully typed),以确保您的内容的准确性。

    人工智能代理

    共置内容减少大型语言模型 (LLM) 所需的上下文。 Intlayer 还附带了一套工具,例如用于测试缺失翻译的 CLILSPMCPagent技能,使 AI 代理的开发者体验 (DX) 更加流畅。

    自动化

    使用您选择的法学硕士,通过自动化在 CI/CD 管道中进行翻译,而费用由您的 AI 提供商承担。 Intlayer 还提供了一个编译器来自动提取内容,以及一个网络平台来帮助在后台翻译

    表现

    将大量 JSON 文件连接到组件可能会导致性能和反应性问题。 Intlayer 可在构建时 (build time)优化您的内容加载。

    无需开发即可扩展

    Intlayer 不仅仅是一个 i18n 解决方案,还提供了一个自托管的可视化编辑器和一个完整的 CMS 来帮助您管理多语言内容实时,与译员、文案人员和其他团队成员无缝协作。内容可以本地和/或远程存储。


    在 React Router v7 应用程序中使用基于文件系统的路由设置 Intlayer 的分步指南

    www.youtube.com

    See Application Template on GitHub.

    创建一个配置文件来配置您的应用程序语言:

    intlayer.config.ts
    import { type IntlayerConfig, Locales } from "intlayer";
    
    const config: IntlayerConfig = {
      internationalization: {
        defaultLocale: Locales.ENGLISH, // 默认语言
        locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH], // 支持的语言列表
      },
    };
    
    export default config;
    通过此配置文件,您可以设置本地化的 URL、中间件重定向、cookie 名称、内容声明的位置和扩展名,禁用控制台中的 Intlayer 日志等。有关可用参数的完整列表,请参阅配置文档

    第三步:在您的 Vite 配置中集成 Intlayer

    将 intlayer 插件添加到您的配置中:

    vite.config.ts
    import { reactRouter } from "@react-router/dev/vite";import { defineConfig } from "vite";import { intlayer } from "vite-intlayer";export default defineConfig({  plugins: [reactRouter(), intlayer()],});
    intlayer() Vite 插件用于将 Intlayer 集成到 Vite 中。它确保内容声明文件的构建,并在开发模式下监视这些文件。它在 Vite 应用中定义了 Intlayer 的环境变量。此外,它还提供别名以优化性能。

    根布局

    app/routes/layout.tsx
    import { IntlayerProvider } from "react-intlayer";import { Outlet } from "react-router";import type { Route } from "./+types/layout";export default function RootLayout({ params }: Route.ComponentProps) {  const { locale } = params;  return (    <IntlayerProvider locale={locale}>      <Outlet />    </IntlayerProvider>  );}

    本地化主页

    app/routes/[lang]/page.tsx
    import { useIntlayer } from "react-intlayer";import { LocalizedLink } from "~/components/localized-link";export default function Page() {  const { title, description, aboutLink } = useIntlayer("page");  return (    <div>      <h1>{title}</h1>      <p>{description}</p>      <nav>        <LocalizedLink to="/about">{aboutLink}</LocalizedLink>      </nav>    </div>  );}
    想了解更多关于 useIntlayer 钩子的内容,请参阅文档
    如果您的应用程序已经存在,您可以结合使用 Intlayer 编译器提取命令 在一秒钟内转换成干个组件。

    第10步:添加HTML属性管理(可选)

    创建一个钩子来管理HTML的 lang 和 dir 属性:

    app/hooks/useI18nHTMLAttributes.tsx
    import { getHTMLTextDir } from "intlayer";import { useEffect } from "react";import { useLocale } from "react-intlayer";export const useI18nHTMLAttributes = () => {  const { locale } = useLocale();  useEffect(() => {    document.documentElement.lang = locale;    document.documentElement.dir = getHTMLTextDir(locale);  }, [locale]);};

    然后在你的根组件中使用它:

    app/routes/layout.tsx
    import { Outlet } from "react-router";import { IntlayerProvider } from "react-intlayer";import { useI18nHTMLAttributes } from "app/hooks/useI18nHTMLAttributes"; // 导入该钩子export default function RootLayout() {  useI18nHTMLAttributes(); // 调用该钩子  return (    <IntlayerProvider>      <Outlet />    </IntlayerProvider>  );}
    1. 提取组件内容

      可选

      如果您有现有的代码库,转换数千个文件可能会非常耗时。

      为了简化此过程,Intlayer 提出了 编译器 / 提取器 来转换您的组件并提取内容。

      要进行设置,您可以在 intlayer.config.ts 文件中添加 compiler 部分:

      intlayer.config.ts
      import { type IntlayerConfig } from "intlayer";
      
      const config: IntlayerConfig = {
        // ... 您的其他配置
        compiler: {
          /**
           * 指示是否应启用编译器。
           */
          enabled: true,
      
          /**
           * 定义输出文件路径
           */
          output: ({ fileName, extension }) => `./${fileName}${extension}`,
      
          /**
           * 指示在转换后是否应保存组件。这样,编译器只需运行一次即可转换应用程序,然后即可将其删除。
           */
          saveComponents: false,
      
          /**
           * 字典键前缀
           */
          dictionaryKeyPrefix: "",
        },
      };
      
      export default config;

      运行提取器以转换组件并提取内容

      bash
      npx intlayer extract

    Configure TypeScript

    Intlayer uses module augmentation to get benefits of TypeScript and make your codebase stronger.

    Ensure your TypeScript configuration includes the autogenerated types:

    tsconfig.json
    {  // ... your existing configurations  include: [    // ... your existing includes    ".intlayer/**/*.ts", // Include the auto-generated types  ],}

    Git Configuration

    It is recommended to ignore the files generated by Intlayer. This allows you to avoid committing them to your Git repository.

    To do this, you can add the following instructions to your .gitignore file:

    .gitignore
    # 忽略 Intlayer 生成的文件.intlayer

    VS Code Extension

    To improve your development experience with Intlayer, you can install the official Intlayer VS Code Extension.

    Install from the VS Code Marketplace

    This extension provides:

    • Autocompletion for translation keys.
    • Real-time error detection for missing translations.
    • Inline previews of translated content.
    • Quick actions to easily create and update translations.

    For more details on how to use the extension, refer to the Intlayer VS Code Extension documentation.


    Go Further

    To go further, you can implement the visual editor or externalize your content using the CMS.


    Documentation References

    This comprehensive guide provides everything you need to integrate Intlayer with React Router v7 using file-system based routing for a fully internationalized application with locale-aware routing and TypeScript support.