如何在nextjs15中,更优雅地实现国际化方案?

1. Nextjs国际化常规方案

在以前,我们实现nextjs国际化,需要引入3个国际化相关的包:next-i18next react-i18next i18next

npm install next-i18next react-i18next 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'), // 语言文件存放的路径
  },
}

在 public/locales 目录下创建相应的语言文件夹,并为每种语言提供 JSON 格式的翻译文件。例如:

// public/locales/en/common.json
{
  "hello": "Hello",
  "welcome": "Welcome to Next.js"
}

最后还需要在 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" 对应的翻译文本。

如果你的页面使用了服务端渲染(SSR)或静态生成(SSG),还需要在 getServerSideProps 或 getStaticProps 中使用 serverSideTranslations 函数来加载翻译文件:

import { serverSideTranslations } from 'next-i18next/serverSideTranslations'

export async function getStaticProps({ locale }) {
  return {
    props: {
      ...(await serverSideTranslations(locale, ['common'])),
    },
  }
}

serverSideTranslations 会自动加载当前语言的翻译文件,并注入到页面组件的 props 中。

2. 实现nextjs国际化,更优雅的方案

首先,我们的Next.js15项目使用App Router模式,实现国际化时,仅需安装2个包:react-i18next i18next

npm install react-i18next i18next