Next.js實現國際化方案完全指南
哈,大家好,我是徐小夕。
最近 Next-Admin 中后臺管理系統已經支持國際化,接下來就和大家分享一下實現國際化的詳細方案,方便大家輕松應用到自己的項目。
github地址:https://github.com/MrXujiang/next-admin
演示地址:http://next-admin.com
內容大綱
- Next-Admin 基本介紹
- Nextjs 國際化常用方案
- 從零實現 Nextjs 國際化方案
- Next-Admin 后期規劃
Next-Admin介紹
圖片
Next-Admin 是一款基于 nextjs最新版 + Antd5.0的開源中后臺(同構)系統,我們使用它可以輕松實現前后端同構項目,支持SSR和CSR, 具體特點如下:
- Next14.0 + antd5.0
- 支持國際化
- 支持主題切換
- 內置數據可視化報表
- 開箱即用的業務頁面模板
- 支持自定義拖拽看板
- 集成辦公白板
- Next全棧最佳實踐
- 支持移動端和PC端自適應
Nextjs 國際化常用方案
圖片
Next.js 的國際化插件有很多,以下是其中一些常用的:
- next-i18next: 一款流行的 Next.js 國際化插件,它提供了豐富的功能,包括多語言路由、服務器端渲染和靜態生成的支持,以及簡單的翻譯文件管理。
- next-intl: 用于 Next.js 的國際化插件,它提供了基于React Intl的國際化解決方案,支持多語言文本和格式化。
- next-translate: 這個插件為 Next.js 提供了簡單的國際化解決方案,支持靜態生成和服務器端渲染,并且易于配置和使用。
在親自體驗了以上幾款插件之后,我選擇了 next-intl, 從擴展和使用靈活性上都非常不錯, 接下來就和大家分享一下如何使用 next-intl 來實現 Next 項目國際化.
從零實現 Nextjs 國際化方案
圖片
1. 首先我們先安裝 next-intl :
pnpm add next-intl
2. 在 Nextjs 項目根目錄中創建 message 目錄, 然后新建語言包文件:
# messages
- zh.json
- en.json
當然如果有其它語言翻譯需求, 也可以添加對應的語言文件,這里給大家推薦一個語言名稱映射表:
圖片
3. 在 src 下新建 i18n.ts 文件,來配置我們的國際化邏輯。
// src/i18n.tsx
import {headers} from 'next/headers';
import {notFound} from 'next/navigation';
import {getRequestConfig} from 'next-intl/server';
import {locales} from './navigation';
export default getRequestConfig(async ({locale}) => {
// Validate that the incoming `locale` parameter is valid
if (!locales.includes(locale as any)) notFound();
const now = headers().get('x-now');
const timeZone = headers().get('x-time-zone') ?? 'Europe/Vienna';
const messages = (await import(`../messages/${locale}.json`)).default;
return {
now: now ? new Date(now) : undefined,
timeZone,
messages,
defaultTranslationValues: {
globalString: 'Global string',
highlight: (chunks) => <strong>{chunks}</strong>
},
formats: {
dateTime: {
medium: {
dateStyle: 'medium',
timeStyle: 'short',
hour12: false
}
}
},
onError(error) {
if (
error.message ===
(process.env.NODE_ENV === 'production'
? 'MISSING_MESSAGE'
: 'MISSING_MESSAGE: Could not resolve `missing` in `Index`.')
) {
// Do nothing, this error is triggered on purpose
} else {
console.error(JSON.stringify(error.message));
}
},
getMessageFallback({key, namespace}) {
return (
'`getMessageFallback` called for ' +
[namespace, key].filter((part) => part != null).join('.')
);
}
};
});
這段邏輯全局配置了 國際化加載的路徑,格式化數據的方式,時間等參數,當然還有更多的邏輯處理可以參考 next-intl 文檔。
需要補充一下 navigation.tsx 這個文件的內容:
import {
createLocalizedPathnamesNavigation,
Pathnames
} from 'next-intl/navigation';
export const defaultLocale = 'zh';
export const locales = ['en', 'zh'] as const;
export const localePrefix =
process.env.NEXT_PUBLIC_LOCALE_PREFIX === 'never' ? 'never' : 'as-needed';
export const pathnames = {
'/': '/',
'/user': '/user',
'/dashboard': '/dashboard',
// '/nested': {
// en: '/next-home',
// zh: '/next-zh-home'
// },
} satisfies Pathnames<typeof locales>;
export const {Link, redirect, usePathname, useRouter} =
createLocalizedPathnamesNavigation({
locales,
localePrefix,
pathnames
});
上面代碼定義了國際化的:
- 默認語言和語言列表
- 路由映射
- 國際化路徑前綴
這樣我們后面在封裝 國際化切換組件的收就會有很好的 ts提示。
4. 配置 next 國際化中間件
我們在 src 目錄下新建 middleware.ts, 內容如下:
import createMiddleware from 'next-intl/middleware';
import {locales, pathnames, localePrefix, defaultLocale} from './navigation';
export default createMiddleware({
defaultLocale,
localePrefix,
pathnames,
locales,
});
export const config = {
// Skip all paths that should not be internationalized
matcher: ['/((?!_next|.*\\..*).*)']
};
這樣國際化方案就初步完成了。接下來我們來具體看看如何在頁面中使用國際化來寫文案。
5. 在組件 / 頁面中使用i18n
next-intl 的國際化定義支持命名空間,我們可以在messages 對應的語言文件中通過嵌套結構來設置命名空間,有序的管理不同頁面的國際化文本:
// zh.json
{
"index": {
"title": "Next-Admin",
"desc": "一款基于NextJS 14.0+ 和 antd5.0 開發的全棧開箱即用的多頁面中后臺管理解決方案",
"log": {
"title": "Next-Admin 進程規劃",
"1": "Next + antd5基礎工程方案",
"2": "國際化語言支持",
"3": "登錄注冊 / 數據大盤 / 業務列表頁面",
"4": "圖標管理 / 素材管理",
"5": "思維導圖 / 流程圖 / 3D可視化頁面",
"6": "頁面搭建引擎 / 表單引擎",
"7": "萬維表"
},
"try": "立即體驗"
},
"global": {
"technological exchanges": "技術交流",
"dashboard": "數據大盤",
"customChart": "'自定義報表",
"monitor": "數據監控",
"userManage": "用戶管理",
"formEngine": "表單引擎",
"board": "辦公白板",
"orderList": "訂單列表",
"resource": "資產管理"
},
// ...
}
這樣我們就可以這樣來使用:
'use client';
import { useTranslations } from 'next-intl';
export default Page(){
const t = useTranslations('global');
return <div> { t('technological exchanges') } </div>
}
同樣我們還可以給國際化文案中使用動態變量:
// en.json
{
"weclome": "Hello {name}!"
}
// page.tsx
t('weclome', {name: 'Next-Admin'}); // "Hello Next-Admin!"
官方文檔中還介紹了如何使用數學計算,時間日期格式化等功能, 整體來說還是非常強大的。
6. 注意事項
由于 next 項目支持客戶端渲染和服務端渲染,所以使用 next-intl 的方式也是有區別的,如果我們在頁面中出現 next-intl 相關的服務端渲染報錯, 可以在頁面同級添加 layout.tsx, 然后做如下封裝:
import { NextIntlClientProvider, useMessages } from 'next-intl';
type Props = {
children: React.ReactNode;
params: {locale: string};
};
export default function LocaleLayout({children, params: { locale }}: Props) {
// Receive messages provided in `i18n.ts`
const messages = useMessages();
return <NextIntlClientProvider locale={locale} messages={messages}>
{children}
</NextIntlClientProvider>
}
這樣就可以解決報錯問題了(本人親自實驗好用)。
同時,這也是基于 nextjs 嵌套布局實現的方案, 為了使用 next-intl, 我們還需要在 next/src/app目錄做如下改造:
next-admin\src\app\[locale]
也就是加一層[locale] 目錄。
好啦, 通過以上的配置我們就可以開心的使用國際化了,全部代碼我已經同步到 Next-Admin 倉庫了, 大家可以開箱即用。
github地址:https://github.com/MrXujiang/next-admin
演示地址:http://next-admin.com