Next.js 國際化
⚠️
此功能僅在 nextra-theme-docs
中可用。
Nextra 支援 Next.js 國際化路由。本文檔說明如何設定和使用它。
新增國際化設定
要在您的 Nextra 應用程式中新增多語言頁面,您需要先在 next.config.mjs
中設定 i18n
next.config.mjs
import nextra from 'nextra'
const withNextra = nextra({
theme: 'nextra-theme-docs',
themeConfig: './theme.config.tsx'
})
export default withNextra({
i18n: {
locales: ['en', 'zh', 'de'],
defaultLocale: 'en'
}
})
**注意**:您可以使用任何格式的 UTS 語言區域識別碼 在 next.config
檔案中定義您的語系,例如帶地區格式的語言 en-US
(美國英語)。
設定文件主題
將 i18n
選項新增到您的 theme.config.jsx
以設定語言下拉選單
theme.config.jsx
i18n: [
{ locale: 'en', name: 'English' },
{ locale: 'zh', name: '中文' },
{ locale: 'de', name: 'Deutsch' },
{ locale: 'ar', name: 'العربية', direction: 'rtl' }
]
自動偵測並重新導向至使用者選擇的語言(選用)
您可以自動偵測使用者偏好的語言,並將其重新導向至網站的相應版本。要實現此目的,請在專案的根目錄中建立一個 middleware.js
檔案,並從 nextra/locales
匯出 Nextra 的 middleware 函式
middleware.js
export { middleware } from 'nextra/locales'
export const config = {
// Matcher ignoring `/_next/` and `/api/`
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|icon.svg|apple-icon.png|manifest).*)'
]
}
⚠️
**注意**:此方法不適用於使用 nextConfig
中的 output: "export"
靜態匯出的國際化網站。
自訂 404 頁面(選用)
在 **Nextra 3** 中,無法為使用共用主題佈局的國際化網站建立 404.mdx
頁面。但是,您可以使用翻譯來實作 404.jsx
頁面。您可以參考 SWR 國際化範例 以獲得有關如何執行此操作的指引。
在 **Nextra 4** 中,您可以為使用共用主題佈局的國際化網站使用自訂的 not-found.jsx
並進行翻譯。有關如何實作的指引,您可以參考 SWR 國際化範例。