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

    使用Intlayer翻译您的Vite and Solid | 国际化(i18n)

    www.youtube.com

    目录

    第一步:安装依赖

    使用 npm 安装所需的包:

    bash
    npx intlayer@canary init --interactive    # v9# npx intlayer init                       # v8
    --interactive 标志是可选的。如果您是 AI 代理,请使用 intlayer-cli init
    该命令将检测您的环境并安装所需的软件包。例如:
    bash
    npm install intlayer solid-intlayernpm install vite-intlayer --save-dev
    • intlayer 提供国际化工具的核心包,用于配置管理、翻译、内容声明、转译以及命令行工具

    • solid-intlayer 将 Intlayer 集成到 Solid 应用中的包。它提供了 Solid 国际化的上下文提供者和钩子。

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

    第 2 步:项目配置

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

    intlayer.config.ts
    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 插件添加到你的配置中。

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

    第4步:声明您的内容

    创建并管理您的内容声明以存储翻译:

    src/app.content.tsx
    import { t, type Dictionary } from "intlayer";
    
    const appContent = {
      key: "app",
      content: {},
    } satisfies Dictionary;
    
    export default appContent;
    您的内容声明可以在应用程序中的任何位置定义,只要它们被包含在 contentDir 目录中(默认是 ./src)。并且文件扩展名需匹配内容声明文件扩展名(默认是 .content.{json,ts,tsx,js,jsx,mjs,cjs,md,mdx,yaml,yml})。
    更多详情,请参考内容声明文档

    第5步:在代码中使用 Intlayer

    在整个应用程序中访问您的内容字典:

    src/App.tsx
    import { createSignal, type Component } from "solid-js";import solidLogo from "./assets/solid.svg";import viteLogo from "/vite.svg";import "./App.css";import { IntlayerProvider, useIntlayer } from "solid-intlayer";const AppContent: Component = () => {  const [count, setCount] = createSignal(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://www.solidjs.com/" target="_blank">          <img            src={solidLogo}            class="logo solid"            alt={content.solidLogo.value}          />        </a>      </div>      <h1>{content.title}</h1>      <div class="card">        <button onClick={() => setCount((count) => count + 1)}>          {content.count({ count: count() })}        </button>        <p>{content.edit}</p>      </div>      <p class="read-the-docs">{content.readTheDocs}</p>    </>  );};const App: Component = () => (  <IntlayerProvider>    <AppContent />  </IntlayerProvider>);export default App;
    在 Solid 中,useIntlayer 返回一个 accessor 函数(例如,`content.)。您必须调用此函数才能访问响应式内容。

    如果您想在 string 属性(如 alttitlehrefaria-label 等)中使用您的内容,可以使用函数的值,例如:

    html
    <img src="{content.image.src.value}" alt="{content.image.value}" /><img src="{content.image.src.toString()}" alt="{content.image.toString()}" /><img src="{String(content.image.src)}" alt="{String(content.image)}" />

    (可选)第6步:更改内容语言

    要更改内容语言,您可以使用 useLocale 钩子提供的 setLocale 函数。此函数允许您设置应用程序的语言环境并相应地更新内容。

    src/components/LocaleSwitcher.tsx
    import { type Component, For } from "solid-js";import { Locales } from "intlayer";import { useLocale } from "solid-intlayer";const LocaleSwitcher: Component = () => {  const { locale, setLocale, availableLocales } = useLocale();  return (    <select      value={locale()}      onChange={(e) => setLocale(e.currentTarget.value as Locales)}    >      <For each={availableLocales}>        {(loc) => (          <option value={loc} selected={loc === locale()}>            {loc}          </option>        )}      </For>    </select>  );};

    (可选)第7步:为应用添加本地化路由

    此步骤的目的是为每种语言创建唯一的路由。这对 SEO 和 SEO 友好的 URL 很有用。 示例:

    plaintext
    - https://example.com/about- https://example.com/es/about- https://example.com/fr/about

    要为您的应用程序添加本地化路由,您可以使用 @solidjs/router

    首先,安装必要的依赖项:

    bash
    npm install @solidjs/router

    然后,用 Router 包装您的应用程序,并使用 localeMap 定义您的路由:

    src/index.tsx
    import { render } from "solid-js/web";import { Router } from "@solidjs/router";import App from "./App";const root = document.getElementById("root");render(  () => (    <Router>      <App />    </Router>  ),  root!);
    src/App.tsx
    import { type Component } from "solid-js";import { Route } from "@solidjs/router";import { localeMap } from "intlayer";import { IntlayerProvider } from "solid-intlayer";import Home from "./pages/Home";import About from "./pages/About";const App: Component = () => (  <IntlayerProvider>    {localeMap(({ locale, urlPrefix }) => (      <Route        path={urlPrefix || "/"}        component={(props: any) => (          <IntlayerProvider locale={locale}>{props.children}</IntlayerProvider>        )}      >        <Route path="/" component={Home} />        <Route path="/about" component={About} />      </Route>    ))}  </IntlayerProvider>);export default App;

    (可选)第8步:当语言环境变化时更改 URL

    要在语言环境更改时更改 URL,您可以使用 useLocale 钩子提供的 onLocaleChange 属性。您可以使用 @solidjs/routeruseNavigateuseLocation 钩子来更新 URL 路径。

    src/components/LocaleSwitcher.tsx
    import { type Component, For } from "solid-js";import { useLocation, useNavigate } from "@solidjs/router";import { getLocalizedUrl } from "intlayer";import { useLocale } from "solid-intlayer";const LocaleSwitcher: Component = () => {  const location = useLocation();  const navigate = useNavigate();  const { locale, setLocale, availableLocales } = useLocale({    onLocaleChange: (loc) => {      const pathWithLocale = getLocalizedUrl(location.pathname, loc);      navigate(pathWithLocale);    },  });  return (    <select      value={locale()}      onChange={(e) => setLocale(e.currentTarget.value as any)}    >      <For each={availableLocales}>        {(loc) => (          <option value={loc} selected={loc === locale()}>            {loc}          </option>        )}      </For>    </select>  );};

    配置 TypeScript

    确保您的 TypeScript 配置包含自动生成的类型。

    tsconfig.json
    {  "compilerOptions": {    // ...  },  "include": ["src", ".intlayer/**/*.ts"],}

    Git 配置

    建议忽略 Intlayer 生成的文件。这样可以避免将它们提交到您的 Git 仓库中。

    为此,您可以将以下指令添加到您的 .gitignore 文件中:

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

    VS Code 扩展

    为了提升您使用 Intlayer 的开发体验,您可以安装官方的 Intlayer VS Code 扩展

    从 VS Code 市场安装

    该扩展提供:

    • 翻译键的自动补全
    • 缺失翻译的实时错误检测
    • 已翻译内容的内联预览
    • 快速操作,轻松创建和更新翻译。

    有关如何使用该扩展的更多详细信息,请参阅Intlayer VS Code 扩展文档


    深入了解

    要进一步使用,您可以实现可视化编辑器或使用内容管理系统(CMS)将内容外部化。