mcpField
N
next-intl-i18n

next-intl-i18n

github.com/canatufkansu开发57 次安装
代码仓库

关于 next-intl-i18n

next-intl-i18n 是面向 Next.js 应用的国际化配置示例,供需要多语言路由和翻译管理的开发者参考。内容涵盖请求配置、消息文件、服务器与客户端组件翻译,以及静态生成和本地化元数据。

主要功能

  1. 01配置语言与默认语言
  2. 02按语言设置路由中间件
  3. 03组织命名空间消息文件
  4. 04支持插值与复数格式
  5. 05实现语言切换器
  6. 06生成静态页面与本地化元数据

适用场景

  1. 01为 Next.js 应用配置多语言路由
  2. 02在服务器和客户端组件中显示翻译
  3. 03添加保留当前路径的语言切换
  4. 04生成本地化页面与元数据

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/canatufkansu/claude-skills --skill next-intl-i18n

安装后在 Claude Code 中输入/next-intl-i18n确认已加载。

详细介绍

next-intl i18n

配置

// i18n.config.ts
export const locales = ['pt-PT', 'en', 'tr', 'es', 'fr', 'de'] as const;
export type Locale = (typeof locales)[number];
export const defaultLocale: Locale = 'pt-PT';
// i18n/request.ts
import { getRequestConfig } from 'next-intl/server';
import { locales, type Locale } from '@/i18n.config';

export default getRequestConfig(async ({ requestLocale }) => {
  let locale = await requestLocale;
  
  if (!locale || !locales.includes(locale as Locale)) {
    locale = 'pt-PT';
  }

  return {
    locale,
    messages: (await import(`@/messages/${locale}.json`)).default,
  };
});

中间件

// middleware.ts
import createMiddleware from 'next-intl/middleware';
import { locales, defaultLocale } from '@/i18n.config';

export default createMiddleware({
  locales,
  defaultLocale,
  localePrefix: 'always',
});

export const config = {
  matcher: ['/', '/(pt-PT|en|tr|es|fr|de)/:path*'],
};

消息文件结构

messages/
├── pt-PT.json
├── en.json
├── tr.json
├── es.json
├── fr.json
└── de.json
// messages/en.json
{
  "nav": {
    "home": "Home",
    "about": "About",
    "services": "Services",
    "book": "Book a Session"
  },
  "hero": {
    "title": "Pilates & Yoga for strength and calm",
    "subtitle": "Transform your body and mind with personalized coaching",
    "cta": "Book Now"
  },
  "common": {
    "learnMore": "Learn More",
    "readMore": "Read More"
  },
  "form": {
    "name": "Name",
    "email": "Email",
    "message": "Message",
    "submit": "Submit",
    "errors": {
      "required": "This field is required",
      "email": "Please enter a valid email"
    }
  }
}

服务端组件

// app/[locale]/page.tsx
import { getTranslations, setRequestLocale } from 'next-intl/server';

type Props = {
  params: Promise<{ locale: string }>;
};

export default async function HomePage({ params }: Props) {
  const { locale } = await params;
  setRequestLocale(locale); // Required for static rendering
  
  const t = await getTranslations('hero');
  
  return (
    <div>
      <h1>{t('title')}</h1>
      <p>{t('subtitle')}</p>
      <button>{t('cta')}</button>
    </div>
  );
}

客户端组件

'use client';

import { useTranslations } from 'next-intl';

export function ContactForm() {
  const t = useTranslations('form');
  
  return (
    <form>
      <label>{t('name')}</label>
      <input placeholder={t('name')} />
      <button type="submit">{t('submit')}</button>
    </form>
  );
}

插值与复数形式

// messages/en.json
{
  "greeting": "Hello, {name}!",
  "items": "You have {count, plural, =0 {no items} =1 {one item} other {# items}}",
  "date": "Last updated: {date, date, medium}"
}
const t = useTranslations();
t('greeting', { name: 'Maria' }); // "Hello, Maria!"
t('items', { count: 5 }); // "You have 5 items"

语言切换器

'use client';

import { useLocale } from 'next-intl';
import { usePathname, useRouter } from 'next/navigation';
import { locales, type Locale } from '@/i18n.config';

const labels: Record<Locale, string> = {
  'pt-PT': 'PT',
  'en': 'EN',
  'tr': 'TR',
  'es': 'ES',
  'fr': 'FR',
  'de': 'DE',
};

export function LanguageSwitcher() {
  const locale = useLocale();
  const pathname = usePathname();
  const router = useRouter();

  const switchLocale = (newLocale: Locale) => {
    // Replace current locale in path
    const newPath = pathname.replace(`/${locale}`, `/${newLocale}`);
    router.push(newPath);
  };

  return (
    <select
      value={locale}
      onChange={(e) => switchLocale(e.target.value as Locale)}
    >
      {locales.map((loc) => (
        <option key={loc} value={loc}>
          {labels[loc]}
        </option>
      ))}
    </select>
  );
}

静态生成

// app/[locale]/layout.tsx
import { locales } from '@/i18n.config';

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }));
}

本地化元数据

import { getTranslations } from 'next-intl/server';
import type { Metadata } from 'next';

type Props = {
  params: Promise<{ locale: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale } = await params;
  const t = await getTranslations({ locale, namespace: 'meta' });

  return {
    title: t('title'),
    description: t('description'),
    alternates: {
      canonical: `/${locale}`,
      languages: {
        'pt-PT': '/pt-PT',
        'en': '/en',
        'tr': '/tr',
        'es': '/es',
        'fr': '/fr',
        'de': '/de',
      },
    },
  };
}

最佳实践

  1. 始终在服务端组件开头调用 setRequestLocale(),以进行静态渲染
  2. 按功能对翻译进行命名空间划分(nav、hero、form、footer)
  3. 确保所有语言区域文件中的键保持一致
  4. 对动态值使用插值,切勿拼接字符串
  5. 切换语言时保留路径

评论

支持 Markdown