Nextjs国际化方案之next-i8next
如何在 Next.js 中使用 next-i18next
实现国际化
next-i18next
是一个非常流行的国际化库,特别适用于 Next.js,它能够帮助你轻松地为应用程序添加多语言支持。通过自动加载语言文件,支持SSR(服务端渲染)以及静态生成等功能,next-i18next
提供了完整的国际化解决方案。
步骤 1: 安装依赖
首先,需要安装 next-i18next
和相关依赖:
npm install next-i18next react-i18next i18next
步骤 2: 配置 next-i18next
在根目录下创建或修改 next-i18next.config.js
文件,用于配置语言、默认语言以及翻译文件路径等。
// next-i18next.config.js
const path = require('path')
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'], // 支持的语言
defaultLocale: 'en', // 默认语言
localePath: path.resolve('./public/locales'), // 语言文件存放的路径
},
}
locales
:定义支持的语言。defaultLocale
:设置默认语言。localePath
:设置翻译文件的位置,通常放在public/locales
目录下。
步骤 3: 创建语言文件
在 public/locales
目录下创建相应的语言文件夹,并为每种语言提供 JSON 格式的翻译文件。
/public
/locales
/en
common.json
/fr
common.json
例如,在 common.json
中,放置英语和法语的翻译内容:
// public/locales/en/common.json
{
"hello": "Hello",
"welcome": "Welcome to Next.js"
}
// public/locales/fr/common.json
{
"hello": "Bonjour",
"welcome": "Bienvenue dans Next.js"
}
步骤 4: 在页面中使用 useTranslation
在 Next.js 页面或组件中使用 useTranslation
钩子来加载和显示相应的翻译。
import { useTranslation } from 'next-i18next'
export default function HomePage() {
const { t } = useTranslation('common') // 加载 common.json 中的翻译
return (
<div>
<h1>{t('hello')}</h1> {/* 显示翻译 */}
<p>{t('welcome')}</p>
</div>
)
}
useTranslation('common')
中的'common'
是指你的 JSON 文件名(不带.json
后缀)。t('hello')
会从common.json
中获取"hello"
对应的翻译文本。
步骤 5: 配置 getServerSideProps
或 getStaticProps
(可选)
如果你的页面使用了服务端渲染(SSR)或静态生成(SSG),你可以在 getServerSideProps
或 getStaticProps
中使用 serverSideTranslations
函数来加载翻译文件:
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
export async function getStaticProps({ locale }) {
return {
props: {
...(await serverSideTranslations(locale, ['common'])),
},
}
}
serverSideTranslations
会自动加载当前语言的翻译文件,并注入到页面组件的 props
中。