使用您最喜欢的AI助手总结文档,并引用此页面和AI提供商
通过将 Intlayer MCP 服务器集成到您的 AI 助手,您可以直接从 ChatGPT、DeepSeek、Cursor、VSCode 等获取所有文档。
查看 MCP 服务器文档此页面的内容已使用 AI 翻译。
查看英文原文的最新版本如果您有改善此文档的想法,请随时通过在GitHub上提交拉取请求来贡献。
文档的 GitHub 链接复制文档 Markdown 到剪贴板
使用 Intlayer、Vite 和 Preact 开始国际化(i18n)
该包正在开发中。有关更多信息,请参见问题。通过点赞该问题,表达您对 Intlayer for Preact 的兴趣。
请参阅 GitHub 上的应用模板。
什么是 Intlayer?
Intlayer 是一个创新的开源国际化(i18n)库,旨在简化现代 Web 应用程序的多语言支持。
使用 Intlayer,您可以:
- 通过组件级声明式字典轻松管理翻译。
- 动态本地化元数据、路由和内容。
- 确保 TypeScript 支持,通过自动生成类型,提升自动补全和错误检测能力。
- 受益于高级功能,如动态语言环境检测和切换。
在 Vite 和 Preact 应用中设置 Intlayer 的分步指南
第一步:安装依赖
使用 npm 安装所需的包:
复制代码到剪贴板
npm install intlayer preact-intlayernpm install vite-intlayer --save-dev
intlayer
preact-intlayer
将 Intlayer 集成到 Preact 应用中的包。它提供了 Preact 国际化的上下文提供者和钩子。vite-intlayer
包含用于将 Intlayer 集成到Vite 打包工具的 Vite 插件,以及用于检测用户首选语言、管理 Cookie 和处理 URL 重定向的中间件。
第2步:配置您的项目
创建一个配置文件来配置您应用程序的语言:
复制代码到剪贴板
import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = { internationalization: { locales: [ Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH, // 您的其他语言 ], defaultLocale: Locales.ENGLISH, },};export default config;
第2步:配置您的项目
创建一个配置文件来配置您应用程序的语言:
复制代码到剪贴板
import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = { internationalization: { locales: [ Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH, // 您的其他语言 ], defaultLocale: Locales.ENGLISH, },};export default config;
通过此配置文件,您可以设置本地化的 URL、中间件重定向、cookie 名称、内容声明的位置和扩展名,禁用 Intlayer 在控制台的日志等。有关可用参数的完整列表,请参阅配置文档。
第3步:在您的 Vite 配置中集成 Intlayer
将 intlayer 插件添加到您的配置中。
复制代码到剪贴板
import { defineConfig } from "vite";import preact from "@preact/preset-vite";import { intlayerPlugin } from "vite-intlayer";// https://vitejs.dev/config/export default defineConfig({ plugins: [preact(), intlayerPlugin()],});
通过此配置文件,您可以设置本地化的 URL、中间件重定向、cookie 名称、内容声明的位置和扩展名,禁用控制台中的 Intlayer 日志等。有关可用参数的完整列表,请参阅配置文档。
第3步:在您的 Vite 配置中集成 Intlayer
将 intlayer 插件添加到您的配置中。
复制代码到剪贴板
import { defineConfig } from "vite";import preact from "@preact/preset-vite";import { intlayerPlugin } from "vite-intlayer";// https://vitejs.dev/config/export default defineConfig({ plugins: [preact(), intlayerPlugin()],});
intlayerPlugin() Vite 插件用于将 Intlayer 集成到 Vite 中。它确保内容声明文件的构建,并在开发模式下监视这些文件。它在 Vite 应用程序中定义了 Intlayer 环境变量。此外,它还提供别名以优化性能。
第4步:声明您的内容
创建并管理您的内容声明以存储翻译:
复制代码到剪贴板
import { t, type Dictionary } from "intlayer";import type { ComponentChildren } from "preact";const appContent = { key: "app", content: { viteLogo: t({ en: "Vite logo", fr: "Logo Vite", es: "Logo Vite", }), preactLogo: t({ en: "Preact logo", fr: "Logo Preact", es: "Logo Preact", }), title: "Vite + Preact", count: t({ zh: "计数是 ", en: "count is ", fr: "le compte est ", es: "el recuento es ", }), edit: t<ComponentChildren>({ zh: ( <> 编辑 <code>src/app.tsx</code> 并保存以测试 HMR </> ), en: ( <> Edit <code>src/app.tsx</code> and save to test HMR </> ), fr: ( <> Éditez <code>src/app.tsx</code> et enregistrez pour tester HMR </> ), es: ( <> Edita <code>src/app.tsx</code> y guarda para probar HMR </> ), }), readTheDocs: t({ zh: "点击 Vite 和 Preact 标志以了解更多信息", en: "Click on the Vite and Preact logos to learn more", fr: "Cliquez sur les logos Vite et Preact pour en savoir plus", es: "Haga clic en los logotipos de Vite y Preact para obtener más información", }), },} satisfies Dictionary;export default appContent;
您的内容声明可以定义在应用程序中的任何位置,只要它们被包含在 contentDir 目录中(默认是 ./src)。并且文件扩展名需匹配内容声明文件扩展名(默认是 .content.{json,ts,tsx,js,jsx,mjs,mjx,cjs,cjx})。
更多详情,请参考内容声明文档。
如果您的内容文件包含 TSX 代码,您可能需要导入 import { h } from "preact";,或者确保您的 JSX pragma 已正确设置为 Preact。
第5步:在代码中使用 Intlayer
在整个应用程序中访问您的内容字典:
复制代码到剪贴板
import { useState } from "preact/hooks";import type { FunctionalComponent } from "preact";import preactLogo from "./assets/preact.svg"; // 假设你有一个 preact.svg 文件import viteLogo from "/vite.svg";import "./app.css"; // 假设你的 CSS 文件名为 app.cssimport { IntlayerProvider, useIntlayer } from "preact-intlayer";const AppContent: FunctionalComponent = () => { const [count, setCount] = useState(0); const content = useIntlayer("app"); return ( <> <div> <a href="https://vitejs.dev" target="_blank"> <img src={viteLogo} class="logo" alt={content.viteLogo.value} /> </a> <a href="https://preactjs.com" target="_blank"> <img src={preactLogo} class="logo preact" alt={content.preactLogo.value} /> </a> </div> <h1>{content.title}</h1> <div class="card"> <button onClick={() => setCount((count) => count + 1)}> {content.count} {count} </button> <p>{content.edit}</p> </div> <p class="read-the-docs">{content.readTheDocs}</p> </> );};const App: FunctionalComponent = () => ( <IntlayerProvider> <AppContent /> </IntlayerProvider>);export default App;
如果您想在字符串属性中使用内容,例如 alt、title、href、aria-label 等,必须调用函数的值,如:
jsx复制代码复制代码到剪贴板
<img src={content.image.src.value} alt={content.image.value} />
注意:在 Preact 中,className 通常写作 class。
要了解更多关于 useIntlayer 钩子的内容,请参阅文档(preact-intlayer 的 API 类似)。
(可选)步骤 6:更改内容语言
要更改内容的语言,可以使用 useLocale 钩子提供的 setLocale 函数。此函数允许您设置应用程序的语言环境并相应地更新内容。
复制代码到剪贴板
import type { FunctionalComponent } from "preact";import { Locales } from "intlayer";import { useLocale } from "preact-intlayer";const LocaleSwitcher: FunctionalComponent = () => { const { setLocale } = useLocale(); return ( <button onClick={() => setLocale(Locales.ENGLISH)}>将语言切换为英语</button> );};export default LocaleSwitcher;
想了解更多关于 useLocale 钩子的内容,请参阅文档(preact-intlayer 的 API 类似)。
(可选)步骤7:为您的应用添加本地化路由
此步骤的目的是为每种语言创建唯一的路由。这对于 SEO 和 SEO 友好的 URL 非常有用。 示例:
复制代码到剪贴板
- https://example.com/about- https://example.com/es/about- https://example.com/fr/about
默认情况下,默认语言的路由不会添加前缀。如果您想为默认语言添加前缀,可以在配置中将 middleware.prefixDefault 选项设置为 true。更多信息请参阅配置文档。
要为您的应用添加本地化路由,您可以创建一个 LocaleRouter 组件来包裹应用的路由,并处理基于语言的路由。以下是使用 preact-iso 的示例:
首先,安装 preact-iso:
复制代码到剪贴板
npm install preact-iso
复制代码到剪贴板
import { type Locales, configuration, getPathWithoutLocale } from "intlayer";import { ComponentChildren, FunctionalComponent } from "preact";import { IntlayerProvider } from "preact-intlayer";import { LocationProvider, useLocation } from "preact-iso";import { useEffect } from "preact/hooks";const { internationalization, middleware } = configuration;const { locales, defaultLocale } = internationalization;const Navigate: FunctionalComponent<{ to: string; replace?: boolean }> = ({ to, replace,}) => { const { route } = useLocation(); useEffect(() => { route(to, replace); }, [to, replace, route]); return null;};/** * 一个处理本地化并用适当的语言环境上下文包裹子组件的组件。 * 它管理基于 URL 的语言环境检测和验证。 *//** * 一个处理本地化的组件,使用适当的语言环境上下文包裹子组件。 * 它管理基于 URL 的语言环境检测和验证。 */const AppLocalized: FunctionalComponent<{ children: ComponentChildren; locale?: Locales;}> = ({ children, locale }) => { const { path: pathname, url } = useLocation(); if (!url) { return null; } const search = url.substring(pathname.length); // 确定当前语言环境,如果未提供则回退到默认语言环境 const currentLocale = locale ?? defaultLocale; // 从路径中移除语言环境前缀以构造基础路径 const pathWithoutLocale = getPathWithoutLocale( pathname // 当前 URL 路径 ); /** * 如果 middleware.prefixDefault 为 true,则默认语言应始终带有前缀。 */ if (middleware.prefixDefault) { // 验证语言 if (!locale || !locales.includes(locale)) { // 重定向到带有更新路径的默认语言 return ( <Navigate to={`/${defaultLocale}/${pathWithoutLocale}${search}`} replace // 用新条目替换当前历史记录 /> ); } // 使用 IntlayerProvider 包裹子组件并设置当前语言 return ( <IntlayerProvider locale={currentLocale}>{children}</IntlayerProvider> ); } else { /** * 当 middleware.prefixDefault 为 false 时,默认语言不带前缀。 * 确保当前语言环境有效且不是默认语言环境。 */ if ( currentLocale.toString() !== defaultLocale.toString() && !locales .filter( (loc) => loc.toString() !== defaultLocale.toString() // 排除默认语言环境 ) .includes(currentLocale) // 检查当前语言环境是否在有效语言环境列表中 ) { // 重定向到无语言环境前缀的路径 return <Navigate to={`${pathWithoutLocale}${search}`} replace />; } // 使用 IntlayerProvider 包裹子组件并设置当前语言环境 return ( <IntlayerProvider locale={currentLocale}>{children}</IntlayerProvider> ); }};const RouterContent: FunctionalComponent<{ children: ComponentChildren;}> = ({ children }) => { const { path } = useLocation(); if (!path) { return null; } const pathLocale = path.split("/")[1] as Locales; const isLocaleRoute = locales .filter((locale) => middleware.prefixDefault || locale !== defaultLocale) .some((locale) => locale.toString() === pathLocale); if (isLocaleRoute) { return <AppLocalized locale={pathLocale}>{children}</AppLocalized>; } return ( <AppLocalized locale={!middleware.prefixDefault ? defaultLocale : undefined} > {children} </AppLocalized> );};/** * 一个设置特定语言环境路由的路由组件。 * 它使用 preact-iso 来管理导航并渲染本地化组件。 */export const LocaleRouter: FunctionalComponent<{ children: ComponentChildren;}> = ({ children }) => ( <LocationProvider> <RouterContent>{children}</RouterContent> </LocationProvider>);
然后,你可以在你的应用中使用 LocaleRouter 组件:
复制代码到剪贴板
import { LocaleRouter } from "./components/LocaleRouter";import type { FunctionalComponent } from "preact";tsx fileName="src/app.tsx" codeFormat="typescript"// ... 你的 AppContent 组件(在步骤5中定义)const App: FunctionalComponent = () => ( <LocaleRouter> <AppContent /> </LocaleRouter>);export default App;
同时,您还可以使用 intLayerMiddlewarePlugin 为您的应用程序添加服务器端路由。该插件将根据 URL 自动检测当前语言环境并设置相应的语言环境 Cookie。如果未指定语言环境,插件将根据用户浏览器的语言偏好确定最合适的语言环境。如果仍未检测到语言环境,则会重定向到默认语言环境。
复制代码到剪贴板
import { defineConfig } from "vite";import preact from "@preact/preset-vite";import { intlayerPlugin, intLayerMiddlewarePlugin } from "vite-intlayer";// https://vitejs.dev/config/export default defineConfig({ plugins: [preact(), intlayerPlugin(), intLayerMiddlewarePlugin()],});
(可选)步骤 8:当语言环境改变时更改 URL
要在语言环境更改时更改 URL,您可以使用 useLocale 钩子提供的 onLocaleChange 属性。同时,您可以使用 preact-iso 中的 useLocation 和 route 来更新 URL 路径。
复制代码到剪贴板
import { useLocation, route } from "preact-iso";import { Locales, getHTMLTextDir, getLocaleName, getLocalizedUrl,} from "intlayer";import { useLocale } from "preact-intlayer";import type { FunctionalComponent } from "preact";const LocaleSwitcher: FunctionalComponent = () => { const location = useLocation(); const { locale, availableLocales, setLocale } = useLocale({ onLocaleChange: (newLocale) => { const currentFullPath = location.url; // preact-iso 提供完整的 URL // 使用更新后的语言环境构建 URL // 例如: /es/about?foo=bar const pathWithLocale = getLocalizedUrl(currentFullPath, newLocale); // 更新 URL 路径 route(pathWithLocale, true); // true 表示替换当前历史记录 }, }); return ( <div> <button popovertarget="localePopover">{getLocaleName(locale)}</button> <div id="localePopover" popover="auto"> {availableLocales.map((localeItem) => ( <a href={getLocalizedUrl(location.url, localeItem)} hreflang={localeItem} aria-current={locale === localeItem ? "page" : undefined} onClick={(e) => { e.preventDefault(); setLocale(localeItem); // 设置语言环境后,程序化导航将由 onLocaleChange 处理 }} key={localeItem} > <span> {/* 语言环境 - 例如 FR */} {localeItem} </span> <span> {/* 语言在其自身语言环境中的名称 - 例如 Français */} {getLocaleName(localeItem, localeItem)} </span> <span dir={getHTMLTextDir(localeItem)} lang={localeItem}> {/* 语言在当前语言环境中的名称 - 例如当前语言环境为 Locales.SPANISH 时显示 Francés */} {getLocaleName(localeItem, locale)} </span> <span dir="ltr" lang={Locales.ENGLISH}> {/* 语言的英文名称 - 例如 French */} {getLocaleName(localeItem, Locales.ENGLISH)} </span> </a> ))} </div> </div> );};export default LocaleSwitcher;
文档参考:
-useLocale 钩子(preact-intlayer 的 API 类似)> - getLocaleName 钩子> - getLocalizedUrl 钩子> - getHTMLTextDir 钩子> - hreflang 属性> - lang 属性> - dir 属性> - aria-current 属性> - Popover API> > - useLocale 钩子(preact-intlayer 的 API 类似)> - getLocaleName 钩子> - getLocalizedUrl 钩子> - getHTMLTextDir 钩子> - hreflang 属性> - lang 属性> - dir 属性> - aria-current 属性> - Popover API
下面是更新后的第9步,增加了说明和优化的代码示例:
(可选)第9步:切换HTML的语言和方向属性
当您的应用支持多语言时,更新<html>标签的lang和dir属性以匹配当前语言环境非常重要。这样做可以确保:
- 无障碍性:屏幕阅读器和辅助技术依赖正确的lang属性来准确发音和解释内容。
- 文本渲染:dir(方向)属性确保文本以正确的顺序呈现(例如,英语为从左到右,阿拉伯语或希伯来语为从右到左),这对可读性至关重要。
- SEO:搜索引擎使用 lang 属性来确定页面的语言,有助于在搜索结果中提供正确的本地化内容。
通过在语言环境变化时动态更新这些属性,您可以确保所有支持语言的用户都能获得一致且无障碍的体验。
实现该 Hook
创建一个自定义 Hook 来管理 HTML 属性。该 Hook 监听语言环境的变化并相应地更新属性:
复制代码到剪贴板
import { useEffect } from "preact/hooks";import { useLocale } from "preact-intlayer";import { getHTMLTextDir } from "intlayer";/** * 根据当前语言环境更新 HTML <html> 元素的 `lang` 和 `dir` 属性。 * - `lang`:通知浏览器和搜索引擎页面的语言。 * - `dir`:确保正确的阅读顺序(例如,英语为 'ltr',阿拉伯语为 'rtl')。 * * 这种动态更新对于正确的文本渲染、无障碍访问和 SEO 至关重要。 */export const useI18nHTMLAttributes = () => { const { locale } = useLocale(); useEffect(() => { // 将语言属性更新为当前的语言环境。 document.documentElement.lang = locale; // 根据当前语言环境设置文本方向。 document.documentElement.dir = getHTMLTextDir(locale); }, [locale]);};
在您的应用程序中使用该 Hook
将该 Hook 集成到您的主组件中,以便在语言环境更改时更新 HTML 属性:
复制代码到剪贴板
import type { FunctionalComponent } from "preact";import { IntlayerProvider } from "preact-intlayer"; // 如果 AppContent 需要,useIntlayer 已经导入import { useI18nHTMLAttributes } from "./hooks/useI18nHTMLAttributes";import "./app.css";// 第5步中定义的 AppContentconst AppWithHooks: FunctionalComponent = () => { // 应用该 Hook 以根据当前语言环境更新 <html> 标签的 lang 和 dir 属性。 useI18nHTMLAttributes(); // 假设 AppContent 是您在第 5 步中定义的主要内容展示组件 return <AppContent />;};const App: FunctionalComponent = () => ( <IntlayerProvider> <AppWithHooks /> </IntlayerProvider>);export default App;
通过应用这些更改,您的应用程序将:
- 确保 语言 (lang) 属性正确反映当前的语言环境,这对于 SEO 和浏览器行为非常重要。
- 根据语言环境调整 文本方向 (dir),提升不同阅读顺序语言的可读性和可用性。
- 提供更无障碍的体验,因为辅助技术依赖这些属性来实现最佳功能。
(可选)步骤10:创建本地化链接组件
为了确保您的应用导航尊重当前语言环境,您可以创建一个自定义的 Link 组件。该组件会自动为内部 URL 添加当前语言的前缀。
这种行为有几个好处:
- SEO 和用户体验:本地化的 URL 有助于搜索引擎正确索引特定语言的页面,并为用户提供其偏好的语言内容。
- 一致性:通过在整个应用中使用本地化链接,您可以确保导航保持在当前语言环境内,避免意外的语言切换。
- 可维护性:将本地化逻辑集中在单个组件中简化了 URL 的管理。
对于使用 preact-iso 的 Preact,通常使用标准的 <a> 标签进行导航,preact-iso 负责路由处理。如果你需要在点击时进行编程式导航(例如,在导航前执行某些操作),可以使用来自 useLocation 的 route 函数。下面是如何创建一个本地化 URL 的自定义锚点组件:
复制代码到剪贴板
import { getLocalizedUrl } from "intlayer";import { useLocale, useLocation, route } from "preact-intlayer"; // 假设 useLocation 和 route 可以通过 preact-intlayer 从 preact-iso 重新导出,或者直接导入// 如果没有重新导出,直接导入:import { useLocation, route } from "preact-iso";import type { JSX } from "preact"; // 用于 HTMLAttributesimport { forwardRef } from "preact/compat"; // 用于转发 refsexport interface LocalizedLinkProps extends JSX.HTMLAttributes<HTMLAnchorElement> { href: string; replace?: boolean; // 可选:替换历史记录状态}/** * 工具函数,用于检查给定的 URL 是否为外部链接。 * 如果 URL 以 http:// 或 https:// 开头,则视为外部链接。 */export const checkIsExternalLink = (href?: string): boolean => /^https?:\/\//.test(href ?? "");/** * 一个自定义的 Link 组件,根据当前语言环境调整 href 属性。 * 对于内部链接,它使用 `getLocalizedUrl` 在 URL 前添加语言前缀(例如 /fr/about)。 * 这确保导航保持在相同的语言环境中。 * 它使用标准的 <a> 标签,但可以通过 preact-iso 的 `route` 触发客户端导航。 */export const LocalizedLink = forwardRef<HTMLAnchorElement, LocalizedLinkProps>( ({ href, children, onClick, replace = false, ...props }, ref) => { const { locale } = useLocale(); const location = useLocation(); // 来自 preact-iso const isExternalLink = checkIsExternalLink(href); const hrefI18n = href && !isExternalLink ? getLocalizedUrl(href, locale) : href; const handleClick = (event: JSX.TargetedMouseEvent<HTMLAnchorElement>) => { if (onClick) { onClick(event); } if ( !isExternalLink && href && // 确保 href 已定义 event.button === 0 && // 左键点击 !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey && // 标准修饰键检查 !props.target // 不在新标签页/窗口打开 ) { event.preventDefault(); if (location.url !== hrefI18n) { // 仅当 URL 不同时才导航 route(hrefI18n, replace); // 使用 preact-iso 的 route } } }; return ( <a href={hrefI18n} ref={ref} onClick={handleClick} {...props}> {children} </a> ); });
工作原理
- 检测外部链接:
辅助函数 checkIsExternalLink 用于判断 URL 是否为外部链接。外部链接保持不变。 - 获取当前语言环境:
useLocale 钩子提供当前的语言环境。 - 本地化 URL:
对于内部链接,getLocalizedUrl 会在 URL 前添加当前语言环境的前缀。 - 客户端导航: handleClick 函数会检查链接是否为内部链接以及是否应阻止标准导航。如果是,则使用 preact-iso 的 route 函数(通过 useLocation 获取或直接导入)来执行客户端导航。这提供了类似 SPA 的行为,而无需完全重新加载页面。
- 返回链接:
该组件返回一个带有本地化 URL 和自定义点击处理程序的 <a> 元素。
配置 TypeScript
Intlayer 使用模块增强来利用 TypeScript 的优势,使您的代码库更健壮。
确保您的 TypeScript 配置包含自动生成的类型。
复制代码到剪贴板
{ // ... 您现有的 TypeScript 配置 "compilerOptions": { // ... "jsx": "react-jsx", "jsxImportSource": "preact", // 推荐用于 Preact 10 及以上版本 // ... }, "include": [ // ... 您现有的 TypeScript 配置 ".intlayer/**/*.ts", // 包含自动生成的类型 ],}
确保您的 tsconfig.json 针对 Preact 进行了设置,特别是 jsx 和 jsxImportSource,或者对于旧版本的 Preact,如果不使用 preset-vite 的默认配置,则需配置 jsxFactory/jsxFragmentFactory。
Git 配置
建议忽略 Intlayer 生成的文件。这样可以避免将它们提交到您的 Git 仓库中。
要做到这一点,您可以将以下指令添加到您的 .gitignore 文件中:
复制代码到剪贴板
# 忽略 Intlayer 生成的文件.intlayer
VS Code 扩展
为了提升您使用 Intlayer 的开发体验,您可以安装官方的 Intlayer VS Code 扩展。
该扩展提供:
- 翻译键的自动补全。
- 缺失翻译的实时错误检测。
- 翻译内容的内联预览。
- 轻松创建和更新翻译的快速操作。
有关如何使用该扩展的更多详细信息,请参阅 Intlayer VS Code 扩展文档。
深入探索
要进一步使用,您可以实现可视化编辑器或使用内容管理系统(CMS)将内容外部化。
文档历史
- 5.5.10 - 2025-06-29:初始化历史