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

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

1个答案

1

Implementing internationalization and localization (i18n) for Next.js Static Site Generation (SSG) pages can be achieved through the following steps:

1. Set up the Next.js Project

First, ensure your Next.js version is 10.0.0 or higher to support built-in i18n routing.

2. Configure next.config.js

In your next.config.js file, enable i18n support and configure language settings and the default locale. For example, if you want to support English and Chinese, configure it as follows:

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

3. Create Language Resource Files

Create a folder to store resource files for different languages. For example, create a folder for each language under public/locales and add the corresponding translation files:

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

In the common.json file, store the corresponding translation key-value pairs:

json
{ "greeting": "Hello" }

4. Use Third-Party Libraries

You can use third-party libraries like next-i18next to simplify and manage language resources. First, install next-i18next:

bash
npm install next-i18next

Then create a next-i18next.config.js configuration file:

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

5. Implement Language Switching

In your Next.js page, use the useTranslation hook provided by next-i18next to get the translation function and display translated text:

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

6. Static Site Generation (SSG)

Ensure your page uses getStaticProps to fetch necessary data, including translation files. For example:

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

This way, Next.js generates static pages for each language during the build process.

7. Deployment and Testing

Deploy your application and verify that pages for each language are correctly generated and accessible.

By following these steps, you can implement multi-language support for Next.js Static Site Generation (SSG) pages.

2024年8月8日 15:15 回复

你的答案