You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Next.js国际化并将en设置为默认语言

配置Next.js App Router实现默认语言根路径访问

要将en设为默认语言,让根路径https://example.com/对应英文,仅波斯语显示为https://example.com/fa,按以下步骤修改配置:

1. 更新next.config.js的国际化设置

在项目根目录的next.config.js中添加或修改i18n配置,关键是设置localePrefix: 'as-needed',这会让默认语言不再显示URL路径段:

/** @type {import('next').NextConfig} */
const nextConfig = {
  i18n: {
    locales: ['en', 'fa'], // 支持的语言列表
    defaultLocale: 'en', // 默认语言
    localePrefix: 'as-needed', // 仅非默认语言显示路径前缀
  },
}

module.exports = nextConfig

2. 重构页面组件以复用代码

为避免重复编写页面逻辑,创建一个共享的本地化页面组件,然后分别为根路径(英文)和波斯语路径创建入口:

创建共享组件src/app/components/LocalizedPage.js

import { getDictionary } from '../dictionaries'

export default async function LocalizedPage({ locale }) {
  const dict = await getDictionary(locale)
  return (
    <>
      <button>{dict.products.cart}</button>
    </>
  )
}

根路径英文页面src/app/page.js

import LocalizedPage from './components/LocalizedPage'

export default async function EnPage() {
  return await LocalizedPage({ locale: 'en' })
}

波斯语页面src/app/fa/page.js

import LocalizedPage from '../components/LocalizedPage'

export default async function FaPage() {
  return await LocalizedPage({ locale: 'fa' })
}

3. 调整字典模块路径

将原[lang]/dictionaries.js移动到src/app/目录下,确保所有页面都能访问:

src/app/dictionaries.js

import 'server-only'

const dictionaries = {
  en: () => import('./dictionaries/en.json').then((module) => module.default),
  fa: () => import('./dictionaries/fa.json').then((module) => module.default),
}

export const getDictionary = async (locale) => dictionaries[locale]()

4. 测试路由

  • 访问https://example.com/将显示英文内容
  • 访问https://example.com/fa将显示波斯语内容

可选:语言切换逻辑

如果需要添加语言切换按钮,在客户端组件中使用useRouter进行跳转:

'use client'
import { useRouter } from 'next/navigation'

export function LanguageSwitcher() {
  const router = useRouter()

  const switchToEn = () => router.push('/')
  const switchToFa = () => router.push('/fa')

  return (
    <div>
      <button onClick={switchToEn}>English</button>
      <button onClick={switchToFa}>فارسی</button>
    </div>
  )
}

内容的提问来源于stack exchange,提问作者Shafizadeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:42:12