乐闻世界logo
搜索文章和话题

How to implement i18n localization in next for static site generated ( SSG ) pages

1 个月前提问
1 个月前修改
浏览次数14

1个答案

1

在 Next.js 中实现静态站点生成(SSG)页面的国际化和本地化(i18n)可以通过以下几个步骤完成:

1. 设置 Next.js 项目

首先确保你的 Next.js 版本支持内置的国际化路由功能(Next.js 10.0.0 及以上版本)。

2. 配置 next.config.js

在你的 next.config.js 文件中,启用 i18n 支持并配置语言环境和默认语言。例如,如果你想支持英语和中文,可以这么配置:

javascript
module.exports = { i18n: { locales: ['en-US', 'zh-CN'], defaultLocale: 'en-US' } }

3. 创建语言资源文件

创建一个文件夹来存储不同语言的资源文件。例如,你可以在 public/locales 下为每种语言创建一个文件夹并添加相应的翻译文件:

shell
public └── locales ├── en-US │ └── common.json └── zh-CN └── common.json

common.json 文件中,存储对应的翻译键值对:

json
{ "greeting": "Hello" }

4. 使用第三方库

可以使用如 next-i18next 这样的第三方库来简化和管理语言资源。首先安装 next-i18next

bash
npm install next-i18next

然后创建一个 next-i18next.config.js 配置文件:

javascript
const { i18n } = require('./next.config'); module.exports = { i18n, localePath: path.resolve('./public/locales') }

5. 实现语言切换

在你的 Next.js 页面中,使用 next-i18next 提供的 useTranslation 钩子来获取翻译函数,并用它来显示翻译后的文本:

javascript
import { useTranslation } from 'next-i18next'; export default function HomePage() { const { t } = useTranslation('common'); return <h1>{t('greeting')}</h1>; }

6. 静态站点生成(SSG)

确保你的页面使用 getStaticProps 来获取必要的数据,包括翻译文件。例如:

javascript
export const getStaticProps = async ({ locale }) => { return { props: { ...await serverSideTranslations(locale, ['common']) } }; };

这样,Next.js 在构建时会为每个语言生成对应的静态页面。

7. 部署和测试

部署你的应用程序,并确保每种语言的页面都正确生成并可以访问。

通过这些步骤,你就可以在 Next.js 中实现支持多语言的静态站点生成(SSG)页面了。

2024年8月8日 15:15 回复

你的答案