Alpha
Lingo.dev Compiler 目前处于 alpha 阶段,尚不稳定,不建议用于生产环境,且 API 可能会在不同版本之间发生变化。
5 分钟内为你的 React 应用接入多语言支持。
前提条件
需要 Node.js 18+,以及一个基于 Next.js(App Router)或 Vite 的 React 应用。
安装#
bash
pnpm install @lingo.dev/compiler配置你的框架#
将配置改为 async,并用 withLingo 包装:
ts
// next.config.ts
import type { NextConfig } from "next";
import { withLingo } from "@lingo.dev/compiler/next";
const nextConfig: NextConfig = {};
export default async function (): Promise<NextConfig> {
return await withLingo(nextConfig, {
sourceRoot: "./app",
sourceLocale: "en",
targetLocales: ["es", "de", "fr"],
models: "lingo.dev",
dev: {
usePseudotranslator: true,
},
});
}添加 LingoProvider#
tsx
// app/layout.tsx
import { LingoProvider } from "@lingo.dev/compiler/react";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<LingoProvider>
<html>
<body>{children}</body>
</html>
</LingoProvider>
);
}身份验证#
bash
npx lingo.dev@latest login这会打开浏览器进行身份验证。免费的 Hobby 方案适用于大多数项目。
如果浏览器身份验证被阻止,请手动将密钥添加到 .env:
bash
LINGODOTDEV_API_KEY=your_key_here运行开发服务器#
bash
npm run devCompiler 会扫描你的 JSX,生成伪翻译(即时生成的模拟翻译,用来直观看到哪些内容会被翻译),并将其注入组件中。元数据会存储在 .lingo/metadata.json 中——请将其提交到版本控制。
添加语言切换器(可选)#
tsx
"use client"; // For Next.js
import { useLingoContext } from "@lingo.dev/compiler/react";
export function LanguageSwitcher() {
const { locale, setLocale } = useLingoContext();
return (
<select value={locale} onChange={(e) => setLocale(e.target.value)}>
<option value="en">English</option>
<option value="es">Espanol</option>
<option value="de">Deutsch</option>
</select>
);
}生成正式翻译#
准备就绪后,关闭 pseudotranslator:
ts
{
dev: {
usePseudotranslator: false,
}
}重启开发服务器。Compiler 会为新增或变更的文本生成真实的 AI 翻译。
