使用您最喜欢的AI助手总结文档,并引用此页面和AI提供商
版本历史
- "更新 Solid useIntlayer API 用法以直接访问属性"v8.9.02026/5/4
- "添加 init 命令"v7.5.92025/12/30
- "更新文档"v6.1.52025/10/3
- "添加 React Router v7 支持"v5.8.22025/9/4
此页面的内容已使用 AI 翻译。
查看英文原文的最新版本If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy doc Markdown to clipboard
使用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 还附带了一套工具,例如用于测试缺失翻译的 CLI、LSP、MCP 和 agent技能,使 AI 代理的开发者体验 (DX) 更加流畅。
自动化
使用您选择的法学硕士,通过自动化在 CI/CD 管道中进行翻译,而费用由您的 AI 提供商承担。 Intlayer 还提供了一个编译器来自动提取内容,以及一个网络平台来帮助在后台翻译。
表现
将大量 JSON 文件连接到组件可能会导致性能和反应性问题。 Intlayer 可在构建时 (build time)优化您的内容加载。
无需开发即可扩展
Intlayer 不仅仅是一个 i18n 解决方案,还提供了一个自托管的可视化编辑器和一个完整的 CMS 来帮助您管理多语言内容实时,与译员、文案人员和其他团队成员无缝协作。内容可以本地和/或远程存储。
在 React Router v7 应用程序中使用基于文件系统的路由设置 Intlayer 的分步指南
See Application Template on GitHub.
创建一个配置文件来配置您的应用程序语言:
复制代码到剪贴板
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 日志等。有关可用参数的完整列表,请参阅配置文档。
文件结构
复制代码到剪贴板
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)
根布局
复制代码到剪贴板
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> );}本地化主页
复制代码到剪贴板
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 编译器 和 提取命令 在一秒钟内转换成干个组件。
关于页面
复制代码到剪贴板
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> );}</Step>
声明您的内容
创建并管理您的内容声明以存储翻译。将内容文件放在路由文件旁边:
复制代码到剪贴板
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;复制代码到剪贴板
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 命令 在一秒内转换数千个组件。
创建区域感知组件
为区域感知导航创建 LocalizedLink 组件:
复制代码到剪贴板
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:
复制代码到剪贴板
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;};创建区域切换器组件
创建一个组件以允许用户更改语言:
复制代码到剪贴板
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 的信息,请参考文档。
添加 HTML 属性管理
创建 hook 以管理 HTML lang 和 dir 属性:
复制代码到剪贴板
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)中使用。
添加中间件
您也可以使用 intlayerProxy 为您的应用程序添加服务器端路由。此插件将自动根据 URL 检测当前区域设置并设置适当的区域 cookie。如果未指定区域设置,该插件将根据用户的浏览器语言偏好确定最合适的区域设置。如果未检测到任何区域设置,它将重定向到默认区域设置。
请注意,要在生产环境中使用intlayerProxy,您需要将vite-intlayer包从devDependencies切换到dependencies。
从 Intlayer v9 开始,intlayerProxy()被直接捆绑到intlayer()插件中,并通过routing.enableProxy选项(默认为true)默认启用。按如下所示单独注册它现在是可选的 — 保留它是为了向后兼容性以及需要控制插件顺序的设置。设置routing.enableProxy: false以选择退出。请参阅 v9 发布说明。
复制代码到剪贴板
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"), }, }), ],});提取您的组件内容
可选如果您有现有的 codebase,转换数千个文件可能会很耗时。
为了简化此过程,Intlayer 提供了一个 compiler / extractor 来转换您的组件并提取内容。
要进行设置,您可以在 intlayer.config.ts 文件中添加一个 compiler 部分:
复制代码到剪贴板
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;运行提取器来转换您的组件并提取内容
复制代码到剪贴板
npx intlayer extract</Steps>
Configure TypeScript
Intlayer uses module augmentation to get benefits of TypeScript and make your codebase stronger.
Ensure your TypeScript configuration includes the autogenerated types:
复制代码到剪贴板
{ // ... 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:
复制代码到剪贴板
# 忽略 Intlayer 生成的文件.intlayerVS 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
- Intlayer Documentation
- React Router v7 Documentation
- React Router fs-routes Documentation
- useIntlayer hook
- useLocale hook
- Content Declaration
- Configuration
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.