简体中文 繁體中文 English 日本語 Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français

站内搜索

搜索

活动公告

11-02 12:46
10-23 09:32
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31
10-23 09:28
通知:签到时间调整为每日4:00(东八区)
10-23 09:26

掌握Next.js国际化技巧让你的网站应用走向全球

3万

主题

424

科技点

3万

积分

大区版主

木柜子打湿

积分
31917

三倍冰淇淋无人之境【一阶】财Doro小樱(小丑装)立华奏以外的星空【二阶】⑨的冰沙

发表于 2025-10-5 13:00:21 | 显示全部楼层 |阅读模式 [标记阅至此楼]

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在全球化的数字时代,网站和应用程序的国际化(Internationalization,通常缩写为i18n)已经成为一项必备功能。国际化不仅能够帮助你的产品触及更广泛的受众,还能提供更好的用户体验,增强品牌在全球市场的影响力。Next.js作为流行的React框架,提供了强大的国际化支持,使开发者能够轻松构建多语言网站。

本文将深入探讨Next.js的国际化技巧,从基础设置到高级优化,帮助你构建真正全球化的网站应用。

Next.js国际化基础

什么是国际化?

国际化是指设计和开发能够适应不同语言和地区而不需要工程更改的应用程序的过程。与国际化相关的是本地化(Localization,简称L10n),它是将国际化应用程序适应特定语言和地区的过程。

Next.js的国际化特性

Next.js从版本10开始引入了内置的国际化支持,并在后续版本中不断改进。主要特性包括:

• 自动区域设置检测
• 基于路径的国际化路由
• 本地化内容管理
• SEO优化的多语言支持

核心概念

在深入Next.js国际化之前,我们需要了解几个核心概念:

1. 区域设置(Locale):表示语言和地区的组合,如en-US(美国英语)、zh-CN(简体中文)等。
2. 默认区域设置:当用户的区域设置无法确定时使用的后备区域设置。
3. 区域设置检测:Next.js如何确定用户的偏好区域设置。
4. 域路由:使用不同的域名提供不同语言的内容。

设置Next.js国际化项目

初始化Next.js项目

首先,让我们创建一个新的Next.js项目:
  1. npx create-next-app my-i18n-app
  2. cd my-i18n-app
复制代码

配置next.config.js

Next.js的国际化配置在next.config.js文件中进行。我们需要添加i18n配置对象:
  1. // next.config.js
  2. module.exports = {
  3.   i18n: {
  4.     // 这些是您支持的所有区域设置
  5.     locales: ['en', 'zh', 'es', 'fr'],
  6.     // 这是默认区域设置,当访问路径中没有区域设置时使用
  7.     defaultLocale: 'en',
  8.     // 这是区域设置检测策略
  9.     localeDetection: true,
  10.     // 可选:域映射
  11.     domains: [
  12.       {
  13.         domain: 'example.com',
  14.         defaultLocale: 'en',
  15.       },
  16.       {
  17.         domain: 'example.cn',
  18.         defaultLocale: 'zh',
  19.       },
  20.     ],
  21.   },
  22. }
复制代码

在这个配置中:

• locales数组列出了我们支持的所有语言。
• defaultLocale指定了默认语言。
• localeDetection控制是否自动检测用户的语言偏好。
• domains(可选)允许你为不同语言使用不同的域名。

安装必要的依赖

为了更好地处理国际化,我们通常需要安装一些额外的库:
  1. npm install next-i18next react-i18next i18next
复制代码

next-i18next是一个流行的Next.js国际化解决方案,它简化了翻译文件的管理和使用。

创建翻译文件

在项目根目录下创建public/locales文件夹,并为每种语言创建子文件夹:
  1. public/
  2.   locales/
  3.     en/
  4.       common.json
  5.       home.json
  6.     zh/
  7.       common.json
  8.       home.json
  9.     es/
  10.       common.json
  11.       home.json
  12.     fr/
  13.       common.json
  14.       home.json
复制代码

每个JSON文件包含对应语言的翻译内容。例如:
  1. // public/locales/en/common.json
  2. {
  3.   "welcome": "Welcome",
  4.   "login": "Login",
  5.   "logout": "Logout",
  6.   "about": "About"
  7. }
  8. // public/locales/zh/common.json
  9. {
  10.   "welcome": "欢迎",
  11.   "login": "登录",
  12.   "logout": "退出",
  13.   "about": "关于"
  14. }
复制代码

初始化i18n

在项目根目录创建i18n.js文件:
  1. // i18n.js
  2. const path = require('path');
  3. module.exports = {
  4.   i18n: {
  5.     defaultLocale: 'en',
  6.     locales: ['en', 'zh', 'es', 'fr'],
  7.     localePath: path.resolve('./public/locales'),
  8.   },
  9.   reloadOnPrerender: process.env.NODE_ENV === 'development',
  10. };
复制代码

然后,创建next-i18next.config.js文件:
  1. // next-i18next.config.js
  2. module.exports = {
  3.   i18n: {
  4.     defaultLocale: 'en',
  5.     locales: ['en', 'zh', 'es', 'fr'],
  6.   },
  7. };
复制代码

修改_app.js

为了在整个应用中使用国际化,我们需要修改pages/_app.js:
  1. // pages/_app.js
  2. import { appWithTranslation } from 'next-i18next';
  3. function MyApp({ Component, pageProps }) {
  4.   return <Component {...pageProps} />;
  5. }
  6. export default appWithTranslation(MyApp);
复制代码

路由国际化

Next.js提供了两种主要的国际化路由策略:基于子路径的路由和基于域的路由。

基于子路径的路由

这是最常见的路由策略,其中语言代码作为URL路径的一部分。例如:
  1. https://example.com/en/about
  2. https://example.com/zh/about
  3. https://example.com/es/about
复制代码

当使用这种策略时,Next.js会自动处理路由,无需额外的配置。例如,创建一个关于页面:
  1. // pages/about.js
  2. import { useTranslation } from 'next-i18next';
  3. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  4. export default function AboutPage() {
  5.   const { t } = useTranslation('common');
  6.   return (
  7.     <div>
  8.       <h1>{t('about')}</h1>
  9.       <p>{t('about_description')}</p>
  10.     </div>
  11.   );
  12. }
  13. export async function getStaticProps({ locale }) {
  14.   return {
  15.     props: {
  16.       ...(await serverSideTranslations(locale, ['common'])),
  17.     },
  18.   };
  19. }
复制代码

基于域的路由

基于域的路由使用不同的域名来服务不同语言的内容。例如:
  1. https://example.com (英语)
  2. https://example.cn (中文)
  3. https://example.es (西班牙语)
复制代码

这种策略需要在next.config.js中配置域名映射,如前面所示。

动态路由的国际化

对于动态路由,如pages/posts/[id].js,国际化处理如下:
  1. // pages/posts/[id].js
  2. import { useRouter } from 'next/router';
  3. import { useTranslation } from 'next-i18next';
  4. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  5. export default function Post({ post }) {
  6.   const router = useRouter();
  7.   const { t } = useTranslation('common');
  8.   return (
  9.     <div>
  10.       <h1>{post.title}</h1>
  11.       <p>{post.content}</p>
  12.     </div>
  13.   );
  14. }
  15. export async function getStaticPaths({ locales }) {
  16.   const posts = await getPosts(); // 假设这是一个获取所有文章的函数
  17.   const paths = [];
  18.   posts.forEach((post) => {
  19.     locales.forEach((locale) => {
  20.       paths.push({
  21.         params: { id: post.id },
  22.         locale,
  23.       });
  24.     });
  25.   });
  26.   return {
  27.     paths,
  28.     fallback: false,
  29.   };
  30. }
  31. export async function getStaticProps({ params, locale }) {
  32.   const post = await getPost(params.id); // 假设这是一个获取特定文章的函数
  33.   return {
  34.     props: {
  35.       post,
  36.       ...(await serverSideTranslations(locale, ['common'])),
  37.     },
  38.   };
  39. }
复制代码

语言切换器

创建一个语言切换器组件,允许用户在不同语言之间切换:
  1. // components/LanguageSwitcher.js
  2. import { useRouter } from 'next/router';
  3. import Link from 'next/link';
  4. const LanguageSwitcher = () => {
  5.   const router = useRouter();
  6.   const { locales, locale, asPath } = router;
  7.   return (
  8.     <div>
  9.       {locales.map((lang) => (
  10.         <Link href={asPath} locale={lang} key={lang}>
  11.           <a style={{ margin: '0 5px', fontWeight: locale === lang ? 'bold' : 'normal' }}>
  12.             {lang}
  13.           </a>
  14.         </Link>
  15.       ))}
  16.     </div>
  17.   );
  18. };
  19. export default LanguageSwitcher;
复制代码

内容翻译

使用useTranslation钩子

在组件中使用useTranslation钩子来访问翻译内容:
  1. import { useTranslation } from 'next-i18next';
  2. function MyComponent() {
  3.   const { t } = useTranslation('common');
  4.   return (
  5.     <div>
  6.       <h1>{t('welcome')}</h1>
  7.       <p>{t('description')}</p>
  8.     </div>
  9.   );
  10. }
复制代码

带参数的翻译

有时我们需要在翻译文本中插入参数:
  1. // public/locales/en/common.json
  2. {
  3.   "welcome_user": "Welcome, {{name}}!",
  4.   "items_count": "You have {{count}} items"
  5. }
复制代码

使用方式:
  1. const { t } = useTranslation('common');
  2. // 简单参数
  3. const welcomeMessage = t('welcome_user', { name: 'John' });
  4. // 复数形式
  5. const itemsMessage = t('items_count', { count: 5 });
复制代码

嵌套翻译

翻译文件可以包含嵌套结构:
  1. // public/locales/en/common.json
  2. {
  3.   "header": {
  4.     "title": "My Website",
  5.     "nav": {
  6.       "home": "Home",
  7.       "about": "About",
  8.       "contact": "Contact"
  9.     }
  10.   }
  11. }
复制代码

使用方式:
  1. const { t } = useTranslation('common');
  2. const homeLink = t('header.nav.home');
  3. const aboutLink = t('header.nav.about');
复制代码

HTML内容的翻译

如果需要翻译包含HTML的内容,可以使用Trans组件:
  1. import { Trans } from 'next-i18next';
  2. function MyComponent() {
  3.   return (
  4.     <Trans i18nKey="welcome_message">
  5.       Welcome to <strong>My Website</strong>! Please <a href="/login">log in</a> to continue.
  6.     </Trans>
  7.   );
  8. }
复制代码

对应的翻译文件:
  1. // public/locales/en/common.json
  2. {
  3.   "welcome_message": "Welcome to <1>My Website</1>! Please <4>log in</4> to continue."
  4. }
复制代码

翻译文件的命名空间

使用命名空间可以更好地组织翻译内容:
  1. // 使用特定命名空间
  2. const { t } = useTranslation('home');
  3. // 使用多个命名空间
  4. const { t } = useTranslation(['common', 'home']);
复制代码

在getStaticProps或getServerSideProps中加载命名空间:
  1. export async function getStaticProps({ locale }) {
  2.   return {
  3.     props: {
  4.       ...(await serverSideTranslations(locale, ['common', 'home'])),
  5.     },
  6.   };
  7. }
复制代码

日期、数字和货币的本地化

日期本地化

使用JavaScript的Intl API来格式化日期:
  1. import { useRouter } from 'next/router';
  2. function DateComponent({ date }) {
  3.   const { locale } = useRouter();
  4.   
  5.   const formattedDate = new Intl.DateTimeFormat(locale, {
  6.     year: 'numeric',
  7.     month: 'long',
  8.     day: 'numeric',
  9.   }).format(new Date(date));
  10.   return <div>{formattedDate}</div>;
  11. }
复制代码

或者使用date-fns库:
  1. npm install date-fns
复制代码
  1. import { format } from 'date-fns';
  2. import { zhCN, enUS, es, fr } from 'date-fns/locale';
  3. const locales = { en: enUS, zh: zhCN, es: es, fr: fr };
  4. function DateComponent({ date }) {
  5.   const { locale } = useRouter();
  6.   
  7.   const formattedDate = format(new Date(date), 'PPP', {
  8.     locale: locales[locale],
  9.   });
  10.   return <div>{formattedDate}</div>;
  11. }
复制代码

数字本地化

使用Intl.NumberFormat来格式化数字:
  1. import { useRouter } from 'next/router';
  2. function NumberComponent({ value }) {
  3.   const { locale } = useRouter();
  4.   
  5.   const formattedNumber = new Intl.NumberFormat(locale).format(value);
  6.   return <div>{formattedNumber}</div>;
  7. }
复制代码

货币本地化

使用Intl.NumberFormat来格式化货币:
  1. import { useRouter } from 'next/router';
  2. function PriceComponent({ value, currency }) {
  3.   const { locale } = useRouter();
  4.   
  5.   const formattedPrice = new Intl.NumberFormat(locale, {
  6.     style: 'currency',
  7.     currency: currency,
  8.   }).format(value);
  9.   return <div>{formattedPrice}</div>;
  10. }
  11. // 使用方式
  12. <PriceComponent value={1234.56} currency="USD" /> // $1,234.56 (en-US)
  13. <PriceComponent value={1234.56} currency="EUR" /> // 1 234,56 € (fr-FR)
复制代码

SEO优化

hreflang标签

hreflang标签告诉搜索引擎不同语言版本之间的关系。在Next.js中,可以通过自定义Document组件添加这些标签:
  1. // pages/_document.js
  2. import Document, { Html, Head, Main, NextScript } from 'next/document';
  3. import { i18n } from '../next-i18next.config';
  4. class MyDocument extends Document {
  5.   render() {
  6.     const currentLocale = this.props.__NEXT_DATA__.query.locale || i18n.defaultLocale;
  7.    
  8.     return (
  9.       <Html lang={currentLocale}>
  10.         <Head>
  11.           {i18n.locales.map((locale) => (
  12.             <link
  13.               key={locale}
  14.               rel="alternate"
  15.               hrefLang={locale}
  16.               href={`https://example.com/${locale}${this.props.__NEXT_DATA__.asPath}`}
  17.             />
  18.           ))}
  19.           <link
  20.             rel="alternate"
  21.             hrefLang="x-default"
  22.             href={`https://example.com/${i18n.defaultLocale}${this.props.__NEXT_DATA__.asPath}`}
  23.           />
  24.         </Head>
  25.         <body>
  26.           <Main />
  27.           <NextScript />
  28.         </body>
  29.       </Html>
  30.     );
  31.   }
  32. }
  33. export default MyDocument;
复制代码

元标签的本地化

确保每个页面的元标签(如标题、描述)也是本地化的:
  1. // pages/about.js
  2. import { useTranslation } from 'next-i18next';
  3. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  4. import Head from 'next/head';
  5. export default function AboutPage() {
  6.   const { t } = useTranslation('common');
  7.   return (
  8.     <>
  9.       <Head>
  10.         <title>{t('about_title')}</title>
  11.         <meta name="description" content={t('about_description')} />
  12.       </Head>
  13.       <div>
  14.         <h1>{t('about')}</h1>
  15.         <p>{t('about_content')}</p>
  16.       </div>
  17.     </>
  18.   );
  19. }
  20. export async function getStaticProps({ locale }) {
  21.   return {
  22.     props: {
  23.       ...(await serverSideTranslations(locale, ['common'])),
  24.     },
  25.   };
  26. }
复制代码

XML站点地图

为多语言网站创建XML站点地图,可以使用next-sitemap包:
  1. npm install next-sitemap
复制代码

创建next-sitemap.config.js文件:
  1. // next-sitemap.config.js
  2. module.exports = {
  3.   siteUrl: 'https://example.com',
  4.   generateRobotsTxt: true,
  5.   exclude: ['/server-sitemap.xml'],
  6.   robotsTxtOptions: {
  7.     additionalSitemaps: [
  8.       'https://example.com/server-sitemap.xml',
  9.     ],
  10.   },
  11. };
复制代码

然后在package.json中添加脚本:
  1. {
  2.   "scripts": {
  3.     "postbuild": "next-sitemap"
  4.   }
  5. }
复制代码

性能优化

按需加载翻译文件

为了避免一次性加载所有翻译文件,可以使用next-i18next的按需加载功能:
  1. // next-i18next.config.js
  2. module.exports = {
  3.   i18n: {
  4.     defaultLocale: 'en',
  5.     locales: ['en', 'zh', 'es', 'fr'],
  6.   },
  7.   // 启用按需加载
  8.   use: [{
  9.     loader: 'i18next-resources-to-backend',
  10.     options: {
  11.       loadPath: (locale, namespace) =>
  12.         `https://cdn.example.com/locales/${locale}/${namespace}.json`,
  13.     },
  14.   }],
  15. };
复制代码

预取翻译文件

为了提高用户体验,可以预取用户可能切换到的语言的翻译文件:
  1. // components/LanguageSwitcher.js
  2. import { useRouter } from 'next/router';
  3. import Link from 'next/link';
  4. import { useTranslation } from 'next-i18next';
  5. const LanguageSwitcher = () => {
  6.   const router = useRouter();
  7.   const { locales, locale, asPath } = router;
  8.   const { i18n } = useTranslation();
  9.   const handlePrefetch = (lang) => {
  10.     i18n.loadLanguages(lang);
  11.   };
  12.   return (
  13.     <div>
  14.       {locales.map((lang) => (
  15.         <Link
  16.           href={asPath}
  17.           locale={lang}
  18.           key={lang}
  19.           onMouseEnter={() => handlePrefetch(lang)}
  20.         >
  21.           <a style={{ margin: '0 5px', fontWeight: locale === lang ? 'bold' : 'normal' }}>
  22.             {lang}
  23.           </a>
  24.         </Link>
  25.       ))}
  26.     </div>
  27.   );
  28. };
  29. export default LanguageSwitcher;
复制代码

使用CDN托管翻译文件

将翻译文件托管在CDN上可以减少服务器负载并提高加载速度:
  1. // next-i18next.config.js
  2. module.exports = {
  3.   backend: {
  4.     loadPath: 'https://cdn.example.com/locales/{{lng}}/{{ns}}.json',
  5.   },
  6. };
复制代码

缓存翻译文件

使用Service Worker缓存翻译文件,提高重复访问的速度:
  1. // public/sw.js
  2. const CACHE_NAME = 'my-i18n-cache-v1';
  3. const urlsToCache = [
  4.   '/locales/en/common.json',
  5.   '/locales/zh/common.json',
  6.   '/locales/es/common.json',
  7.   '/locales/fr/common.json',
  8. ];
  9. self.addEventListener('install', (event) => {
  10.   event.waitUntil(
  11.     caches.open(CACHE_NAME)
  12.       .then((cache) => cache.addAll(urlsToCache))
  13.   );
  14. });
  15. self.addEventListener('fetch', (event) => {
  16.   event.respondWith(
  17.     caches.match(event.request)
  18.       .then((response) => {
  19.         if (response) {
  20.           return response;
  21.         }
  22.         return fetch(event.request);
  23.       })
  24.   );
  25. });
复制代码

然后在pages/_app.js中注册Service Worker:
  1. // pages/_app.js
  2. import { useEffect } from 'react';
  3. function MyApp({ Component, pageProps }) {
  4.   useEffect(() => {
  5.     if ('serviceWorker' in navigator) {
  6.       navigator.serviceWorker.register('/sw.js')
  7.         .then((registration) => {
  8.           console.log('Service Worker registered with scope:', registration.scope);
  9.         })
  10.         .catch((error) => {
  11.           console.log('Service Worker registration failed:', error);
  12.         });
  13.     }
  14.   }, []);
  15.   return <Component {...pageProps} />;
  16. }
  17. export default MyApp;
复制代码

高级技巧

动态加载翻译

对于大型应用,可能需要动态加载翻译文件,而不是在构建时包含所有翻译:
  1. // utils/i18n.js
  2. import i18n from 'i18next';
  3. import { initReactI18next } from 'react-i18next';
  4. const resources = {
  5.   en: {
  6.     translation: () => import('../public/locales/en/common.json'),
  7.   },
  8.   zh: {
  9.     translation: () => import('../public/locales/zh/common.json'),
  10.   },
  11.   es: {
  12.     translation: () => import('../public/locales/es/common.json'),
  13.   },
  14.   fr: {
  15.     translation: () => import('../public/locales/fr/common.json'),
  16.   },
  17. };
  18. i18n
  19.   .use(initReactI18next)
  20.   .init({
  21.     resources,
  22.     lng: 'en',
  23.     fallbackLng: 'en',
  24.     interpolation: {
  25.       escapeValue: false,
  26.     },
  27.   });
  28. export default i18n;
复制代码

基于用户的地理位置自动选择语言

可以使用用户的地理位置信息来自动选择语言:
  1. // utils/detectLocale.js
  2. export async function detectLocale() {
  3.   try {
  4.     const response = await fetch('https://ipapi.co/json/');
  5.     const data = await response.json();
  6.    
  7.     // 根据国家代码映射到语言
  8.     const countryToLocale = {
  9.       'CN': 'zh',
  10.       'US': 'en',
  11.       'ES': 'es',
  12.       'FR': 'fr',
  13.       // 更多映射...
  14.     };
  15.    
  16.     return countryToLocale[data.country] || 'en';
  17.   } catch (error) {
  18.     console.error('Error detecting locale:', error);
  19.     return 'en';
  20.   }
  21. }
复制代码

然后在getServerSideProps中使用:
  1. // pages/_app.js
  2. import { detectLocale } from '../utils/detectLocale';
  3. function MyApp({ Component, pageProps }) {
  4.   return <Component {...pageProps} />;
  5. }
  6. MyApp.getInitialProps = async ({ ctx }) => {
  7.   const locale = await detectLocale();
  8.   
  9.   return {
  10.     pageProps: {
  11.       initialLocale: locale,
  12.     },
  13.   };
  14. };
  15. export default MyApp;
复制代码

使用翻译管理系统

对于大型项目,手动管理翻译文件可能变得困难。可以考虑使用翻译管理系统(TMS),如Transifex、Crowdin或Phrase:
  1. // utils/translationApi.js
  2. const API_KEY = 'your-api-key';
  3. const PROJECT_ID = 'your-project-id';
  4. export async function fetchTranslations(locale) {
  5.   try {
  6.     const response = await fetch(
  7.       `https://api.transifex.com/projects/${PROJECT_ID}/resource/${locale}/`,
  8.       {
  9.         headers: {
  10.           'Authorization': `Bearer ${API_KEY}`,
  11.         },
  12.       }
  13.     );
  14.     const data = await response.json();
  15.     return data.content;
  16.   } catch (error) {
  17.     console.error('Error fetching translations:', error);
  18.     return {};
  19.   }
  20. }
复制代码

案例研究:电子商务网站的国际化

让我们看一个电子商务网站如何实现国际化:
  1. // pages/products/[id].js
  2. import { useRouter } from 'next/router';
  3. import { useTranslation } from 'next-i18next';
  4. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  5. import { format } from 'date-fns';
  6. import { enUS, zhCN, es, fr } from 'date-fns/locale';
  7. const locales = { en: enUS, zh: zhCN, es: es, fr: fr };
  8. export default function ProductPage({ product }) {
  9.   const { locale } = useRouter();
  10.   const { t } = useTranslation(['common', 'products']);
  11.   const formattedPrice = new Intl.NumberFormat(locale, {
  12.     style: 'currency',
  13.     currency: product.currency,
  14.   }).format(product.price);
  15.   const formattedDate = format(new Date(product.releaseDate), 'PPP', {
  16.     locale: locales[locale],
  17.   });
  18.   return (
  19.     <div>
  20.       <h1>{product.name[locale]}</h1>
  21.       <p>{product.description[locale]}</p>
  22.       <p>{t('products:price')}: {formattedPrice}</p>
  23.       <p>{t('products:release_date')}: {formattedDate}</p>
  24.       <button>{t('common:add_to_cart')}</button>
  25.     </div>
  26.   );
  27. }
  28. export async function getStaticPaths({ locales }) {
  29.   const products = await getProducts(); // 假设这是一个获取所有产品的函数
  30.   const paths = [];
  31.   products.forEach((product) => {
  32.     locales.forEach((locale) => {
  33.       paths.push({
  34.         params: { id: product.id },
  35.         locale,
  36.       });
  37.     });
  38.   });
  39.   return {
  40.     paths,
  41.     fallback: 'blocking',
  42.   };
  43. }
  44. export async function getStaticProps({ params, locale }) {
  45.   const product = await getProduct(params.id); // 假设这是一个获取特定产品的函数
  46.   return {
  47.     props: {
  48.       product,
  49.       ...(await serverSideTranslations(locale, ['common', 'products'])),
  50.     },
  51.     revalidate: 60, // ISR: 每60秒重新生成页面
  52.   };
  53. }
复制代码

总结与展望

Next.js提供了强大的国际化支持,使开发者能够轻松构建全球化的网站应用。通过本文介绍的技术和最佳实践,你可以:

1. 设置和管理多语言路由
2. 实现内容翻译和本地化
3. 处理日期、数字和货币的格式化
4. 优化SEO以提高国际可见性
5. 优化性能以提供更好的用户体验
6. 实现高级的国际化功能

随着全球化趋势的加强,网站和应用程序的国际化将变得越来越重要。Next.js团队也在不断改进其国际化功能,未来可能会有更多强大的特性被引入。

作为开发者,我们应该将国际化视为开发过程中的一个重要部分,而不是事后添加的功能。通过采用本文介绍的最佳实践,你可以确保你的Next.js应用能够真正走向全球,为不同语言和地区的用户提供优质的体验。

无论你是在构建一个小型博客还是一个大型电子商务平台,掌握Next.js的国际化技巧都将帮助你的产品在全球市场中取得成功。希望本文能够为你的国际化之旅提供有价值的指导和启发。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.