Alpha
Lingo.dev Compiler 目前仍处于 alpha 阶段,稳定性尚未达到生产要求,不建议用于生产环境,且 API 可能会在不同版本之间发生变化。
Lingo.dev Compiler 通过 withLingo() 配置包装器接入 Next.js App Router。它会改造你的构建流程,生成按 locale 拆分的 bundle,并支持 React Server Components、Webpack 和 Turbopack,且无需修改任何组件代码。
前置要求#
要求
- Next.js 14+(使用 App Router)
- Node.js 18+
- 已安装
@lingo.dev/compiler
安装#
pnpm install @lingo.dev/compiler配置 next.config.ts#
使用 withLingo 包装你的 Next.js 配置。配置函数必须是 async——这是必需的,因为 withLingo 会在构建过程中执行异步初始化。
// 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", "ja"],
models: "lingo.dev",
dev: {
usePseudotranslator: true,
},
});
}必须使用异步配置
配置必须以 async 函数的形式导出,不能导出为普通对象。否则编译器将无法完成初始化,构建也会失败。详情请参阅 故障排查。
添加 LingoProvider#
使用 LingoProvider 包装根布局,在整个组件树中启用 locale 上下文:
// 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>
);
}LingoProvider 负责 locale 解析、持久化和词典加载,同时兼容 Server Components 和 Client Components。
Server Components 与 Client Components#
编译器会无感处理这两类组件:
| 组件类型 | 翻译工作方式 |
|---|---|
| React Server Components | 翻译会在服务端于请求时解析,不会带来任何客户端 JS 额外开销。 |
Client Components("use client") | 翻译会被打包进客户端 chunk 中,并可使用 useLingoContext() 进行 locale 切换。 |
| 共享组件 | 在两种上下文中都能正常工作,编译器会自动识别渲染环境。 |
// app/page.tsx - Server Component (default)
export default function Home() {
return <h1>Welcome to our app</h1>;
// Renders translated text with zero client JS
}// app/components/greeting.tsx - Client Component
"use client";
export function Greeting() {
return <p>Hello, world</p>;
// Translations included in client bundle
}打包器支持#
withLingo() 包装器兼容 Next.js 支持的两种打包器:
| 打包器 | 支持情况 | 说明 |
|---|---|---|
| Webpack | 完整支持 | 默认打包器,无需额外配置。 |
| Turbopack | 完整支持 | 使用 next dev --turbopack 启用,编译器会自动识别 Turbopack。 |
sourceRoot 配置#
sourceRoot 选项用于告诉编译器,哪些目录包含可翻译组件。对于 Next.js App Router 项目,通常是 ./app:
{
sourceRoot: "./app",
}如果你的组件位于 ./app 之外(例如共享的 components/ 目录),请将 sourceRoot 设置为它们的公共父目录:
{
sourceRoot: ".",
}sourceRoot 设得越宽,扫描的文件就越多。对于大型项目,建议尽可能缩小其范围,以减少构建时间。或者,你也可以使用 useDirective: true,并只在需要翻译的文件中添加 'use i18n'。详情请参阅 项目结构。
