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

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

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

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

    目录

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

    react-i18nexti18next 等主流解决方案相比,Intlayer 是一个集成了优化功能的解决方案,例如:

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

    完整的 React Router 覆盖

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

    捆绑尺寸

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

    </Accordion>

    可维护性

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

    人工智能代理

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

    自动化

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

    </Accordion>

    表现

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

    无需开发即可扩展

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


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

    www.youtube.com
    ide.intlayer.org
    intlayer-react-router-v7.vercel.app

    See Application Template on GitHub.

    1. 安装依赖项

      使用您喜欢的包管理器安装必要的包:

      bash
      npm install intlayer react-intlayer
      npm install vite-intlayer --save-dev
      npm install @react-router/fs-routes --save-dev
      npx intlayer init
      
      • intlayer

      提供国际化工具的核心包,用于配置管理、翻译、内容声明、转译和 CLI 命令

      • react-intlayer 与 React 应用集成 Intlayer 的包。它为 React 国际化提供上下文提供者和钩子。

      • vite-intlayer 包括用于将 Intlayer 与 Vite bundler 集成的 Vite 插件,以及用于检测用户首选语言、管理 cookie 和处理 URL 重定向的中间件。

      • @react-router/fs-routes 为 React Router v7 启用基于文件系统的路由的包。

    2. 配置您的项目

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

      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 日志等。有关可用参数的完整列表,请参阅配置文档
    3. 在您的 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 环境变量。此外,它还提供别名以优化性能。
    4. 配置 React Router v7 文件系统路由

    5. 设置您的路由配置以使用带有 flatRoutes 的文件系统路由:

      app/routes.ts
      import type { RouteConfig } from "@react-router/dev/routes";
      import { flatRoutes } from "@react-router/fs-routes";
      import { configuration } from "intlayer";
      
      const routes: RouteConfig = flatRoutes({
        // 忽略内容声明文件被视为路由
        ignoredRouteFiles: configuration.content.fileExtensions.map(
          (fileExtension) => `**/*${fileExtension}`
        ),
      });
      
      export default routes;
      
      @react-router/fs-routes 中的 flatRoutes 函数启用了基于文件系统的路由,其中 routes/ 目录中的文件结构决定了应用程序的路由。ignoredRouteFiles 选项确保 Intlayer 内容声明文件(.content.ts 等)不被视为路由文件。
      1. 创建根布局

        通过文件系统路由,你使用一个平面命名约定,其中点号 (.) 表示路径段,圆括号 () 表示可选段。

        在你的 app/routes/ 目录中创建以下文件:

        文件结构

        bash
        app/
        ├── root.tsx                         # 用于本地化路由的布局包装器
        └──routes/
            ├── ($locale)._index.tsx         # 主页 (/, /es, 等)
            ├── ($locale)._index.content.ts  # 主页内容
            ├── ($locale).about.tsx          # 关于页面 (/about, /es/about, 等)
            └── ($locale).about.content.ts   # 关于页面内容
        

        命名约定:

        • ($locale) - 本地化参数的可选动态段
        • _layout - 包装子路由的布局路由
        • _index - 索引路由(在父路径处呈现)
        • . (点号) - 分隔路径段(例如,($locale).about/:locale?/about

        根布局

        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>
          );
        }
        

        关于页面

        app/routes/($locale).about.tsx
        import { getIntlayer, validatePrefix } from "intlayer";
        import { useIntlayer } from "react-intlayer";
        import { data } from "react-router";
        
        import { LocaleSwitcher } from "~/components/locale-switcher";
        import { Navbar } from "~/components/navbar";
        
        import type { Route } from "./+types/($locale).about";
        
        export const loader = ({ params }: Route.LoaderArgs) => {
          const { locale } = params;
        
          const { isValid } = validatePrefix(locale);
        
          if (!isValid) {
            throw data("Locale not supported", { status: 404 });
          }
        };
        
        export const meta: Route.MetaFunction = ({ params }) => {
          const content = getIntlayer("about", params.locale);
        
          return [
            { title: content.title },
            { content: content.description, name: "description" },
          ];
        };
        
        export default function AboutPage() {
          const { title, content, homeLink } = useIntlayer("about");
        
          return (
            <div>
              <h1>{title}</h1>
              <p>{content}</p>
              <nav>
                <LocalizedLink to="/">{homeLink}</LocalizedLink>
              </nav>
            </div>
          );
        }
        
      2. 声明您的内容

        创建并管理您的内容声明以存储翻译。将内容文件放在路由文件旁边:

        app/routes/($locale)._index.content.ts
        import { t, type Dictionary } from "intlayer";
        
        const pageContent = {
          key: "page",
          content: {
            title: t({
              zh: "欢迎使用 React Router v7 + Intlayer",
              en: "Welcome to React Router v7 + Intlayer",
              es: "Bienvenido a React Router v7 + Intlayer",
              fr: "Bienvenue sur React Router v7 + Intlayer",
            }),
            description: t({
              zh: "使用 React Router v7 和 Intlayer 轻松构建多语言应用程序。",
              en: "Build multilingual applications with ease using React Router v7 and Intlayer.",
              es: "Cree aplicaciones multilingües fácilmente usando React Router v7 y Intlayer.",
              fr: "Créez des applications multilingues facilement avec React Router v7 et Intlayer.",
            }),
            aboutLink: t({
              zh: "了解我们",
              en: "Learn About Us",
              es: "Aprender Sobre Nosotros",
              fr: "En savoir plus sur nous",
            }),
          },
        } satisfies Dictionary;
        
        export default pageContent;
        
        app/routes/($locale).about.content.ts
        import { t, type Dictionary } from "intlayer";
        
        const aboutContent = {
          key: "about",
          content: {
            title: t({
              zh: "关于我们",
              en: "About Us",
              es: "Sobre Nosotros",
              fr: "À propos de nous",
            }),
            content: t({
              zh: "这是关于页面的内容。",
              en: "This is the about page content.",
              es: "Este es el contenido de la página de información.",
              fr: "Ceci est le contenu de la page à propos.",
            }),
            homeLink: t({
              zh: "主页",
              en: "Home",
              es: "Inicio",
              fr: "Accueil",
            }),
          },
        } satisfies Dictionary;
        
        export default aboutContent;
        
        您的内容声明可以在应用程序中的任何位置定义,只要它们包含在 contentDir 目录中(默认为 ./app)。并且匹配内容声明文件扩展名(默认为 .content.{json,ts,tsx,js,jsx,mjs,cjs,md,mdx,yaml,yml})。
        有关更多详细信息,请参考内容声明文档
        如果您的应用程序已经存在,您可以使用 Intlayer Compiler 以及 extract 命令 在一秒内转换数千个组件。
      3. 创建区域感知组件

        为区域感知导航创建 LocalizedLink 组件:

        app/components/localized-link.tsx
        import type { FC } from "react";
        
        import { getLocalizedUrl, type LocalesValues } from "intlayer";
        import { useLocale } from "react-intlayer";
        import { Link, type LinkProps, type To } from "react-router";
        
        const isExternalLink = (to: string) => /^(https?:)?\/\//.test(to);
        
        export const locacalizeTo = (to: To, locale: LocalesValues): To => {
          if (typeof to === "string") {
            if (isExternalLink(to)) {
              return to;
            }
        
            return getLocalizedUrl(to, locale);
          }
        
          if (isExternalLink(to.pathname ?? "")) {
            return to;
          }
        
          return {
            ...to,
            pathname: getLocalizedUrl(to.pathname ?? "", locale),
          };
        };
        
        export const LocalizedLink: FC<LinkProps> = (props) => {
          const { locale } = useLocale();
        
          return <Link {...props} to={locacalizeTo(props.to, locale)} />;
        };
        

        如果您想导航到本地化路由,可以使用 useLocalizedNavigate hook:

        app/hooks/useLocalizedNavigate.ts
        import { useLocale } from "react-intlayer";
        import { type NavigateOptions, type To, useNavigate } from "react-router";
        
        import { locacalizeTo } from "~/components/localized-link";
        
        export const useLocalizedNavigate = () => {
          const navigate = useNavigate();
          const { locale } = useLocale();
        
          const localizedNavigate = (to: To, options?: NavigateOptions) => {
            const localedTo = locacalizeTo(to, locale);
        
            navigate(localedTo, options);
          };
        
          return localizedNavigate;
        };
        
      4. 创建区域切换器组件

        创建一个组件以允许用户更改语言:

        app/components/locale-switcher.tsx
        import type { FC } from "react";
        
        import {
          getHTMLTextDir,
          getLocaleName,
          getLocalizedUrl,
          getPathWithoutLocale,
          Locales,
        } from "intlayer";
        import { useIntlayer, useLocale } from "react-intlayer";
        import { Link, useLocation } from "react-router";
        
        export const LocaleSwitcher: FC = () => {
          const { localeSwitcherLabel } = useIntlayer("locale-switcher");
          const { pathname } = useLocation();
        
          const { availableLocales, locale } = useLocale();
        
          const pathWithoutLocale = getPathWithoutLocale(pathname);
        
          return (
            <ol>
              {availableLocales.map((localeItem) => (
                <li key={localeItem}>
                  <Link
                    aria-current={localeItem === locale ? "page" : undefined}
                    aria-label={`${localeSwitcherLabel.value} ${getLocaleName(localeItem)}`}
                    reloadDocument // 重新加载页面以应用新的区域设置
                    to={getLocalizedUrl(pathWithoutLocale, localeItem)}
                  >
                    <span>
                      {/* 区域设置 - 例如 FR */}
                      {localeItem}
                    </span>
                    <span>
                      {/* 语言在其自己的区域设置中 - 例如 Français */}
                      {getLocaleName(localeItem, locale)}
                    </span>
                    <span dir={getHTMLTextDir(localeItem)} lang={localeItem}>
                      {/* 语言在当前区域设置中 - 例如当前区域设置为 Locales.SPANISH 时的 Francés */}
                      {getLocaleName(localeItem)}
                    </span>
                    <span dir="ltr" lang={Locales.ENGLISH}>
                      {/* 英文语言 - 例如 French */}
                      {getLocaleName(localeItem, Locales.ENGLISH)}
                    </span>
                  </Link>
                </li>
              ))}
            </ol>
          );
        };
        
        若要了解更多关于 useLocale hook 的信息,请参考文档
      5. 添加 HTML 属性管理

        创建 hook 以管理 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]);
        };
        

        此 hook 已在第 5 步中显示的布局组件(($locale)._layout.tsx)中使用。

      6. 添加中间件

        您也可以使用 intlayerProxy 为您的应用程序添加服务器端路由。此插件将自动根据 URL 检测当前区域设置并设置适当的区域 cookie。如果未指定区域设置,该插件将根据用户的浏览器语言偏好确定最合适的区域设置。如果未检测到任何区域设置,它将重定向到默认区域设置。

        请注意,要在生产环境中使用 intlayerProxy,您需要将 vite-intlayer 包从 devDependencies 切换到 dependencies
        从 Intlayer v9 开始,intlayerProxy() 被直接捆绑到 intlayer() 插件中,并通过 routing.enableProxy 选项(默认为 true)默认启用。按如下所示单独注册它现在是可选的 — 保留它是为了向后兼容性以及需要控制插件顺序的设置。设置 routing.enableProxy: false 以选择退出。请参阅 v9 发布说明
        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({
              proxy: {
                ignore: (req) => req.url?.startsWith("/api"),
              },
            }),
          ],
        });
        
      7. 提取您的组件内容

        可选

        如果您有现有的 codebase,转换数千个文件可能会很耗时。

        为了简化此过程,Intlayer 提供了一个 compiler / extractor 来转换您的组件并提取内容。

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

        intlayer.config.ts
        import { type IntlayerConfig } from "intlayer";
        
        const config: IntlayerConfig = {
          // ... 您的配置的其余部分
          compiler: {
            /**
             * 指示编译器是否应该启用。
             */
            enabled: true,
        
            /**
             * 定义输出文件路径
             */
            output: ({ fileName, extension }) => `./${fileName}${extension}`,
        
            /**
             * 指示转换后是否应保存组件。
             *
             * - 如果为 `true`,编译器将重写磁盘中的组件文件。所以转换将是永久的,编译器将跳过下一个过程的转换。这样,编译器可以转换应用程序,然后可以将其删除。
             *
             * - 如果为 `false`,编译器将仅在构建输出中将 `useIntlayer()` 函数调用注入到代码中,并保持基本 codebase 完整。转换将仅在内存中完成。
             */
            saveComponents: false,
        
            /**
             * 字典键前缀
             */
            dictionaryKeyPrefix: "",
          },
        };
        
        export default config;
        

        运行提取器来转换您的组件并提取内容

        bash
        npx intlayer extract
        
        从 v9 开始,intlayerCompiler 包含在 intlayer 插件中。所以您不需要手动添加它。

        更新您的 vite.config.ts 以包含 intlayerCompiler 插件:

        vite.config.ts
        import { defineConfig } from "vite";
        import { intlayer, intlayerCompiler } from "vite-intlayer";
        
        export default defineConfig({
          plugins: [
            intlayer(),
            intlayerCompiler(), // 添加编译器插件
          ],
        });
        
        bash
        npm run build # 或 npm run dev
        

      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.