Next.js i18n 国际化 next-intl
Next.js i18n About 2,221 words安装
npm install next-intl
创建相应文件夹
- 根目录:
messages文件夹en.json:英文zh.json:中文xx.json:对应语言
- 源码目录:
i18n文件夹request.ts
├── messages
│ ├── en.json
│ └── ...
├── next.config.ts
└── src
├── i18n
│ └── request.ts
└── app
├── layout.tsx
└── page.tsx
编辑 next.config.ts
import {NextConfig} from 'next';
import createNextIntlPlugin from 'next-intl/plugin';
const nextConfig: NextConfig = {};
const withNextIntl = createNextIntlPlugin();
export default withNextIntl(nextConfig);
编辑 request.ts
import {getRequestConfig} from 'next-intl/server';
export default getRequestConfig(async () => {
// 根据逻辑修改
const locale = 'en';
// const store = await cookies();
// const locale = store.get('locale')?.value || 'en';
return {
locale,
messages: (await import(`../../messages/${locale}.json`)).default
};
});
编辑 app/layout.ts
使用NextIntlClientProvider包裹children。
import {NextIntlClientProvider} from 'next-intl';
export default async function RootLayout({children}: LayoutProps<'/'>) {
return (
<html>
<body>
<NextIntlClientProvider>{children}</NextIntlClientProvider>
</body>
</html>
);
}
i18n json
en
{
"HomePage": {
"title": "Hello world!",
"description": "Hello {username}"
}
}
zh
{
"HomePage": {
"title": "你好世界!",
"description": "你好 {username}"
}
}
Client Component
useTranslations参数表示json的节点。
import {useTranslations} from 'next-intl';
export default function HomePage() {
const t = useTranslations('HomePage');
return <h1>{t('title')}</h1>;
}
Server Component
使用t的第二个对象,传入动态参数。
import {getTranslations} from 'next-intl/server';
export default async function HomePage() {
const user = await fetchUser();
const t = await getTranslations('HomePage');
return (
<PageLayout title={t('description', {username: user.name})}>
<UserDetails user={user} />
</PageLayout>
);
}
错误信息
⨯ Error:
useTranslationsis not callable within an async component. Please refer to https://next-intl.dev/docs/environments/server-client-components#async-components
错误原因
服务端组件(async标注的组件)中使用了useTranslations。
应使用getTranslations方法。
GitHub
https://github.com/amannn/next-intl/
官方文档
Views: 11 · Posted: 2025-10-25
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...