哈,大家好,我是徐小夕。
最近 Next-Admin 中后臺管理系統已經支持國際化,接下來就和大家分享一下實現國際化的詳細方案,方便大家輕松應用到自己的項目。
github地址:https://github.com/MrXujiang/next-admin
演示地址:http://next-admin.com
圖片
Next-Admin 是一款基于 nextjs最新版 + Antd5.0的開源中后臺(同構)系統,我們使用它可以輕松實現前后端同構項目,支持SSR和CSR, 具體特點如下:
圖片
Next.js 的國際化插件有很多,以下是其中一些常用的:
在親自體驗了以上幾款插件之后,我選擇了 next-intl, 從擴展和使用靈活性上都非常不錯, 接下來就和大家分享一下如何使用 next-intl 來實現 Next 項目國際化.
圖片
pnpm add next-intl
# messages- zh.json- en.json
當然如果有其它語言翻譯需求, 也可以添加對應的語言文件,這里給大家推薦一個語言名稱映射表:
圖片
// src/i18n.tsximport {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提示。
我們在 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|.*//..*).*)']};
這樣國際化方案就初步完成了。接下來我們來具體看看如何在頁面中使用國際化來寫文案。
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.tsxt('weclome', {name: 'Next-Admin'}); // "Hello Next-Admin!"
官方文檔中還介紹了如何使用數學計算,時間日期格式化等功能, 整體來說還是非常強大的。
由于 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
本文鏈接:http://www.www897cc.com/showinfo-26-81240-0.htmlNext.js實現國際化方案完全指南
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 深入理解Java虛擬機:方法區詳解
下一篇: 第三方組件與依賴管理簡介