跳转到内容

Next.js 设置

Terminal window
npm install tyndale-next
  1. 更新你的 Next.js 配置

    next.config.mjs
    import { withTyndaleConfig } from 'tyndale-next/config';
    export default withTyndaleConfig({
    // your existing Next.js config
    });
  2. 添加中间件

    middleware.ts
    import { createTyndaleMiddleware } from 'tyndale-next/middleware';
    export default createTyndaleMiddleware();
    export const config = {
    matcher: ['/((?!api|_next|_tyndale|.*\\..*).*)'],
    };

    这会处理 locale 检测、重定向到带有 locale 前缀的路由,并将当前激活的 locale 持久化到 cookie 中。

  3. 将服务端 provider 添加到你的布局中

    app/[locale]/layout.tsx
    import { getDirection, TyndaleServerProvider } from 'tyndale-next/server';
    export default async function RootLayout({
    children,
    params,
    }: {
    children: React.ReactNode;
    params: Promise<{ locale: string }>;
    }) {
    const { locale } = await params;
    return (
    <html lang={locale} dir={getDirection(locale)}>
    <body>
    <TyndaleServerProvider locale={locale}>
    {children}
    </TyndaleServerProvider>
    </body>
    </html>
    );
    }

    TyndaleServerProvider 会在服务器端加载 locale 数据。请在服务端组件中使用 getDirection(locale),或在客户端组件中使用 useDirection(),自行设置 <html dir>

  • withTyndaleConfig 会读取 tyndale.config.json,注入 Tyndale 在运行时使用的构建期环境变量,并为 tyndale-react 设置别名,让你的应用共享同一个 provider 上下文
  • 中间件会将请求重定向到带 locale 前缀的路由,规范化 locale 别名,并为下游渲染设置 locale cookie/header
  • TyndaleServerProvider 会在服务器端加载翻译,并通过 React context 提供给所有组件