如何在next-i18next中仅为特定页面启用本地化路由
解决Next.js中仅指定页面生成本地化路由的问题
要实现仅index和service页面生成本地化路由,contact-us和disclaimer页面保持默认路由不生成本地化版本,可按以下步骤操作:
1. 保留全局i18n基础配置
在next.config.js中维持原有的i18n全局配置,这是本地化功能的基础:
// next.config.js module.exports = { i18n: { locales: ['en', 'fr'], // 你的目标语言列表 defaultLocale: 'en', }, };
2. 为需要本地化的页面配置路由生成
在pages/index.js和pages/service.js中,通过getStaticPaths生成本地化路由,并在getStaticProps中加载翻译资源:
示例(index.js):
import { useTranslation } from 'next-i18next'; import { serverSideTranslations } from 'next-i18next/serverSideTranslations'; export default function Home() { const { t } = useTranslation('home'); return <div>{t('welcome')}</div>; } export async function getStaticPaths({ locales }) { // 为所有语言生成本地化路径 return { paths: locales.map(locale => ({ params: {}, locale, })), fallback: false, }; } export async function getStaticProps({ locale }) { return { props: { ...(await serverSideTranslations(locale, ['home'])), }, }; }
service.js的配置逻辑完全一致,只需调整翻译命名空间即可。
3. 禁用非本地化页面的路由生成
在pages/contact-us.js和pages/disclaimer.js中,修改getStaticPaths仅生成默认语言路径,且不加载翻译资源:
示例(contact-us.js):
export default function ContactUs() { // 不使用useTranslation钩子 return <div>Contact Us Page</div>; } export async function getStaticPaths() { // 仅生成默认语言的路径,不生成本地化版本 return { paths: [{ params: {} }], fallback: false, }; } export async function getStaticProps() { // 不加载翻译资源,直接返回空props return { props: {}, }; }
disclaimer.js的配置逻辑同上。
4. 验证效果
完成配置后,运行项目:
- 可正常访问
/en、/fr、/en/service、/fr/service等本地化路由 - 访问
/fr/contact-us或/fr/disclaimer会返回404,因为未生成对应本地化路由,仅能通过/contact-us、/disclaimer访问
如果你的项目使用getServerSideProps而非getStaticProps,处理逻辑类似:不在非本地化页面中调用serverSideTranslations,且不处理locale参数即可。
内容的提问来源于stack exchange,提问作者Dhrub Kumar Sharma
相关产品推荐
相关产品推荐

