Next.js實(shí)現(xiàn)國際化方案完全指南
哈,大家好,我是徐小夕。
最近 Next-Admin 中后臺管理系統(tǒng)已經(jīng)支持國際化,接下來就和大家分享一下實(shí)現(xiàn)國際化的詳細(xì)方案,方便大家輕松應(yīng)用到自己的項(xiàng)目。
github地址:https://github.com/MrXujiang/next-admin
演示地址:http://next-admin.com
內(nèi)容大綱
- Next-Admin 基本介紹
 - Nextjs 國際化常用方案
 - 從零實(shí)現(xiàn) Nextjs 國際化方案
 - Next-Admin 后期規(guī)劃
 
Next-Admin介紹
圖片
Next-Admin 是一款基于 nextjs最新版 + Antd5.0的開源中后臺(同構(gòu))系統(tǒng),我們使用它可以輕松實(shí)現(xiàn)前后端同構(gòu)項(xiàng)目,支持SSR和CSR, 具體特點(diǎn)如下:
- Next14.0 + antd5.0
 - 支持國際化
 - 支持主題切換
 - 內(nèi)置數(shù)據(jù)可視化報(bào)表
 - 開箱即用的業(yè)務(wù)頁面模板
 - 支持自定義拖拽看板
 - 集成辦公白板
 - Next全棧最佳實(shí)踐
 - 支持移動端和PC端自適應(yīng)
 
Nextjs 國際化常用方案
圖片
Next.js 的國際化插件有很多,以下是其中一些常用的:
- next-i18next: 一款流行的 Next.js 國際化插件,它提供了豐富的功能,包括多語言路由、服務(wù)器端渲染和靜態(tài)生成的支持,以及簡單的翻譯文件管理。
 - next-intl: 用于 Next.js 的國際化插件,它提供了基于React Intl的國際化解決方案,支持多語言文本和格式化。
 - next-translate: 這個插件為 Next.js 提供了簡單的國際化解決方案,支持靜態(tài)生成和服務(wù)器端渲染,并且易于配置和使用。
 
在親自體驗(yàn)了以上幾款插件之后,我選擇了 next-intl, 從擴(kuò)展和使用靈活性上都非常不錯, 接下來就和大家分享一下如何使用 next-intl 來實(shí)現(xiàn) Next 項(xiàng)目國際化.
從零實(shí)現(xiàn) Nextjs 國際化方案
圖片
1. 首先我們先安裝 next-intl :
pnpm add next-intl2. 在 Nextjs 項(xiàng)目根目錄中創(chuàng)建 message 目錄, 然后新建語言包文件:
# messages
- zh.json
- en.json當(dāng)然如果有其它語言翻譯需求, 也可以添加對應(yīng)的語言文件,這里給大家推薦一個語言名稱映射表:
圖片
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('.')
      );
    }
  };
});這段邏輯全局配置了 國際化加載的路徑,格式化數(shù)據(jù)的方式,時間等參數(shù),當(dāng)然還有更多的邏輯處理可以參考 next-intl 文檔。
需要補(bǔ)充一下 navigation.tsx 這個文件的內(nèi)容:
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
    });上面代碼定義了國際化的:
- 默認(rèn)語言和語言列表
 - 路由映射
 - 國際化路徑前綴
 
這樣我們后面在封裝 國際化切換組件的收就會有很好的 ts提示。
4. 配置 next 國際化中間件
我們在 src 目錄下新建 middleware.ts, 內(nèi)容如下:
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 對應(yīng)的語言文件中通過嵌套結(jié)構(gòu)來設(shè)置命名空間,有序的管理不同頁面的國際化文本:
// zh.json
{
    "index": {
        "title": "Next-Admin",
        "desc": "一款基于NextJS 14.0+ 和 antd5.0 開發(fā)的全棧開箱即用的多頁面中后臺管理解決方案",
        "log": {
            "title": "Next-Admin 進(jìn)程規(guī)劃",
            "1": "Next + antd5基礎(chǔ)工程方案",
            "2": "國際化語言支持",
            "3": "登錄注冊 / 數(shù)據(jù)大盤 / 業(yè)務(wù)列表頁面",
            "4": "圖標(biāo)管理 / 素材管理",
            "5": "思維導(dǎo)圖 / 流程圖 / 3D可視化頁面",
            "6": "頁面搭建引擎 / 表單引擎",
            "7": "萬維表"
        },
        "try": "立即體驗(yàn)"
    },
    "global": {
        "technological exchanges": "技術(shù)交流",
        "dashboard": "數(shù)據(jù)大盤",
        "customChart": "'自定義報(bào)表",
        "monitor": "數(shù)據(jù)監(jiān)控",
        "userManage": "用戶管理",
        "formEngine": "表單引擎",
        "board": "辦公白板",
        "orderList": "訂單列表",
        "resource": "資產(chǎn)管理"
    },
    // ...
}這樣我們就可以這樣來使用:
'use client';
import { useTranslations } from 'next-intl';
export default Page(){
  const t = useTranslations('global');
  
  return <div> { t('technological exchanges') } </div>
}同樣我們還可以給國際化文案中使用動態(tài)變量:
// en.json
{
  "weclome": "Hello {name}!"
}
// page.tsx
t('weclome', {name: 'Next-Admin'}); // "Hello Next-Admin!"官方文檔中還介紹了如何使用數(shù)學(xué)計(jì)算,時間日期格式化等功能, 整體來說還是非常強(qiáng)大的。
6. 注意事項(xiàng)
由于 next 項(xiàng)目支持客戶端渲染和服務(wù)端渲染,所以使用 next-intl 的方式也是有區(qū)別的,如果我們在頁面中出現(xiàn) next-intl 相關(guān)的服務(wù)端渲染報(bào)錯, 可以在頁面同級添加 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>
  }這樣就可以解決報(bào)錯問題了(本人親自實(shí)驗(yàn)好用)。
同時,這也是基于 nextjs 嵌套布局實(shí)現(xiàn)的方案, 為了使用 next-intl, 我們還需要在 next/src/app目錄做如下改造:
next-admin\src\app\[locale]也就是加一層[locale] 目錄。
好啦, 通過以上的配置我們就可以開心的使用國際化了,全部代碼我已經(jīng)同步到 Next-Admin 倉庫了, 大家可以開箱即用。
github地址:https://github.com/MrXujiang/next-admin
演示地址:http://next-admin.com















 
 
 









 
 
 
 