next.js app目錄 i18n國際化簡單實現

来源:https://www.cnblogs.com/tandk-blog/p/18149028/how-nextjs-app-simply-make-i18n
-Advertisement-
Play Games

XQuery 是 XML 數據的查詢語言,類似於 SQL 是資料庫的查詢語言。它被設計用於查詢 XML 數據。 XQuery 示例 for $x in doc("books.xml")/bookstore/book where $x/price > 30 order by $x/title retu ...


最近在用next寫一個多語言的項目,找了好久沒找到簡單實現的教程,實踐起來感覺都比較複雜,最後終於是在官方文檔找到了,結合網上找到的代碼demo,終於實現了,在這裡簡單總結一下。

此教程適用於比較簡單的項目實現,如果你是剛入門next,並且不想用太複雜的方式去實現一個多語言項目,那麼這個教程就挺適合你的。

此教程適用於app目錄的next項目。

先貼一下參閱的連接:

官方教程: next i18n 文檔

可參閱的代碼demo

實現思路

結合文件結構解說一下大致邏輯:

image

  • i18n-config.ts只是一個全局管理多語言簡寫的枚舉文件,其他文件可以引用這個文件,這樣就不會出現不同文件對不上的情況。
  • middleware.ts做了一層攔截,在用戶訪問localhost:3000的時候能通過請求頭判斷用戶常用的語言,配合app目錄多出來的[lang]目錄,從而實現跳轉到localhost:3000/zh這樣。
  • dictionaries文件夾下放各語言的json欄位,通過欄位的引用使頁面呈現不同的語種。
    事實上每個頁面的layout.tsxpage.tsx都會將語言作為參數傳入,在對應的文件里,再調用get-dictionaries.ts文件里的方法就能讀取到對應的json文件里的內容了。

大致思路是這樣,下麵貼對應的代碼。

/i18n-config.ts

export const i18n = {
    defaultLocale: "en",
    // locales: ["en", "zh", "es", "hu", "pl"],
    locales: ["en", "zh"],
} as const;

export type Locale = (typeof i18n)["locales"][number];

/middleware.ts,需要先安裝兩個依賴,這兩個依賴用於判斷用戶常用的語言:

npm install @formatjs/intl-localematcher
npm install negotiator

然後才是/middleware.ts的代碼:

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

import { i18n } from "./i18n-config";

import { match as matchLocale } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";

function getLocale(request: NextRequest): string | undefined {
  // Negotiator expects plain object so we need to transform headers
  const negotiatorHeaders: Record<string, string> = {};
  request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));

  // @ts-ignore locales are readonly
  const locales: string[] = i18n.locales;

  // Use negotiator and intl-localematcher to get best locale
  let languages = new Negotiator({ headers: negotiatorHeaders }).languages(
    locales,
  );

  const locale = matchLocale(languages, locales, i18n.defaultLocale);

  return locale;
}

export function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname;

  // // `/_next/` and `/api/` are ignored by the watcher, but we need to ignore files in `public` manually.
  // // If you have one
  // if (
  //   [
  //     '/manifest.json',
  //     '/favicon.ico',
  //     // Your other files in `public`
  //   ].includes(pathname)
  // )
  //   return

  // Check if there is any supported locale in the pathname
  const pathnameIsMissingLocale = i18n.locales.every(
    (locale) =>
      !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`,
  );

  // Redirect if there is no locale
  if (pathnameIsMissingLocale) {
    const locale = getLocale(request);

    // e.g. incoming request is /products
    // The new URL is now /en-US/products
    return NextResponse.redirect(
      new URL(
        `/${locale}${pathname.startsWith("/") ? "" : "/"}${pathname}`,
        request.url,
      ),
    );
  }
}

export const config = {
  // Matcher ignoring `/_next/` and `/api/`
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};

/dictionaries下的因項目而異,可以看個參考:
image

文件以語言簡寫命名,/i18n-config.ts里的locales有什麼語言,這裡就有多少個對應的文件就行了。

/get-dictionaries.ts

import "server-only";
import type { Locale } from "./i18n-config";

// We enumerate all dictionaries here for better linting and typescript support
// We also get the default import for cleaner types
const dictionaries = {
  en: () => import("./dictionaries/en.json").then((module) => module.default),
  zh: () => import("./dictionaries/zh.json").then((module) => module.default),
};

export const getDictionary = async (locale: Locale) => dictionaries[locale]?.() ?? dictionaries.en();

實際使用可以做個參考:
image

到這裡其實就實現了,但是下麵的事情需要註意:

如果你的項目有集成了第三方需要配知道middleware的地方,比如clerk,需要調試一下是否衝突。

如果你不知道clerk是什麼,那麼下麵可以不用看,下麵將以clerk為例,描述一下可能遇到的問題和解決方案。

Clerk適配

clerk是一個可以快速登錄的第三方庫,用這個庫可以快速實現用戶登錄的邏輯,包括Google、GitHub、郵箱等的登錄。

clerk允許你配置哪些頁面是公開的,哪些頁面是需要登錄之後才能看的,如果用戶沒登錄,但是卻訪問了需要登錄的頁面,就會返回401,跳轉到登錄頁面。

就是這裡衝突了,因為我們實現多語言的邏輯是,用戶訪問localhost:3000的時候判斷用戶常用的語言,從而實現跳轉到localhost:3000/zh這樣。

這兩者實現都在middleware.ts文件中,上面這種配置會有衝突,這兩者只有一個能正常跑通,而我們想要的效果是兩者都能跑通,既能自動跳轉到登錄頁面,也能自動跳轉到常用語言頁面。

技術問題定位:這是因為你重寫了middleware方法,導致不會執行Clerk的authMiddleware方法,視覺效果上,就是多語言導致了Clerk不會自動跳轉登錄。

所以要把上面的middleware方法寫到authMiddleware方法里的beforeAuth里去,Clerk官方有說明: Clerk authMiddleware說明

image

所以現在/middleware.ts文件內的內容變成了:

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { authMiddleware } from "@clerk/nextjs";
import { i18n } from "./i18n-config";
import { match as matchLocale } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";

function getLocale(request: NextRequest): string | undefined {
  // Negotiator expects plain object so we need to transform headers
  const negotiatorHeaders: Record<string, string> = {};
  request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));

  // @ts-ignore locales are readonly
  const locales: string[] = i18n.locales;

  // Use negotiator and intl-localematcher to get best locale
  let languages = new Negotiator({ headers: negotiatorHeaders }).languages(
    locales,
  );

  const locale = matchLocale(languages, locales, i18n.defaultLocale);

  return locale;
}

export const config = {
  // Matcher ignoring `/_next/` and `/api/`
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
  // matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};

export default authMiddleware({
  publicRoutes: ['/anyone-can-visit-this-route'],
  ignoredRoutes: ['/no-auth-in-this-route'],
  beforeAuth: (request) => {
    const pathname = request.nextUrl.pathname;

    // // `/_next/` and `/api/` are ignored by the watcher, but we need to ignore files in `public` manually.
    // // If you have one
    if (
      [
        '/manifest.json',
        '/favicon.ico',
        '/serviceWorker.js',
        '/en/sign-in'
        // Your other files in `public`
      ].includes(pathname)
    )
      return

    // Check if there is any supported locale in the pathname
    const pathnameIsMissingLocale = i18n.locales.every(
      (locale) =>
        !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`,
    );

    // Redirect if there is no locale
    if (pathnameIsMissingLocale) {
      const locale = getLocale(request);

      // e.g. incoming request is /products
      // The new URL is now /en-US/products
      return NextResponse.redirect(
        new URL(
          `/${locale}${pathname.startsWith("/") ? "" : "/"}${pathname}`,
          request.url,
        ),
      );
    }
  }
});

這樣就OK了,大功告成。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、Canvas Canvas組件是一種圖形渲染組件,它提供了一個畫布(canvas),開發者可以在上面繪製各種圖形、文本等。Canvas組件通常用於創建游戲、數據可視化等需要動態繪製圖形的應用程式。 Canvas組件提供了多個API,開發者可以使用這些API進行繪製操作。常用的API包括繪製矩 ...
  • 函數是一組一起執行一個任務的語句。 您可以把代碼劃分到不同的函數中。如何劃分代碼到不同的函數中是由您來決定的,但在邏輯上,劃分通常是根據每個函數執行一個特定的任務來進行的。 函數聲明告訴編譯器函數的名稱、返回類型和參數。函數定義提供了函數的實際主體。 函數定義 函數就是包裹在花括弧中的代碼塊,前面使 ...
  • 介紹 本示例介紹使用了Tab組件實現自定義增刪Tab頁簽的功能。該場景多用於瀏覽器等場景。 效果圖預覽 使用說明: 點擊新增按鈕,新增Tab頁面。 點擊刪除按鈕,刪除Tab頁面。 實現思路 設置Tab組件的barHeight為0,隱藏組件自帶的TabBar。 Tabs() { ... } .barH ...
  • 主題搗鼓日記 sakura版本(YYDS) 主要框架都沒怎麼動,功能挺完整的。但是如果要DIY還是得自己把代碼捋一遍,不然從哪改起都不知道,註釋不能說完全沒用。。。 搗鼓了兩天兩夜,還是有很多細節沒改好,main.js翻了四五遍,看評論區發現諸多細節還要改CSS文件,太難了。。前端都忘得差不多了,趕 ...
  • 一、題目及運行環境 1.小組成員 2252331 與 2252336 2.題目 小學老師要每周給同學出300道四則運算練習題。 這個程式有很多種實現方式: C/C++ C#/VB.net/Java Excel Unix Shell Emacs/Powershell/Vbscript Perl Pyt ...
  • 什麼是介面重覆提交? 介面重覆提交指的是在網路通信中,同一個請求被客戶端多次發送到伺服器端的情況。這種情況可能由於多種原因導致,例如用戶在等待期間多次點擊提交按鈕、網路超時後客戶端重新發送請求、客戶端發送的請求在網路傳輸過程中出現重覆等。 介面重覆提交可能會導致多種問題,當伺服器收到重覆請求時,可能 ...
  • 其他章節請看: vue3 快速入門 系列 他API 前面我們已經學習了 vue3 的一些基礎知識,本篇將繼續講解一些常用的其他api,以及較完整的分析vue2 和 vue3 的改變。 淺層響應式數據 shallowRef shallow 中文:“淺層的” shallowRef:淺的 ref()。 先 ...
  • 零代碼指的是藉助VuePress 通過簡單配置,幫助我們生成靜態網站。 零成本指的是藉助GitHub Pages 或者Gitee Pages部署網站,讓互聯網上的小伙伴能訪問到它 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:本文代碼示例演示瞭如何在WPF中使用LiveCharts庫創建動態條形圖。通過創建數據模型、ViewModel和在XAML中使用`CartesianChart`控制項,你可以輕鬆實現圖表的數據綁定和動態更新。我將通過清晰的步驟指南包括詳細的中文註釋,幫助你快速理解並應用這一功能。 先上效果: 在 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • 概述:本示例演示了在WPF應用程式中實現多語言支持的詳細步驟。通過資源字典和數據綁定,以及使用語言管理器類,應用程式能夠在運行時動態切換語言。這種方法使得多語言支持更加靈活,便於維護,同時提供清晰的代碼結構。 在WPF中實現多語言的一種常見方法是使用資源字典和數據綁定。以下是一個詳細的步驟和示例源代 ...
  • 描述(做一個簡單的記錄): 事件(event)的本質是一個委托;(聲明一個事件: public event TestDelegate eventTest;) 委托(delegate)可以理解為一個符合某種簽名的方法類型;比如:TestDelegate委托的返回數據類型為string,參數為 int和 ...
  • 1、AOT適合場景 Aot適合工具類型的項目使用,優點禁止反編 ,第一次啟動快,業務型項目或者反射多的項目不適合用AOT AOT更新記錄: 實實在在經過實踐的AOT ORM 5.1.4.117 +支持AOT 5.1.4.123 +支持CodeFirst和非同步方法 5.1.4.129-preview1 ...
  • 總說周知,UWP 是運行在沙盒裡面的,所有許可權都有嚴格限制,和沙盒外交互也需要特殊的通道,所以從根本杜絕了 UWP 毒瘤的存在。但是實際上 UWP 只是一個應用模型,本身是沒有什麼許可權管理的,許可權管理全靠 App Container 沙盒控制,如果我們脫離了這個沙盒,UWP 就會放飛自我了。那麼有沒... ...
  • 目錄條款17:讓介面容易被正確使用,不易被誤用(Make interfaces easy to use correctly and hard to use incorrectly)限制類型和值規定能做和不能做的事提供行為一致的介面條款19:設計class猶如設計type(Treat class de ...
  • title: 從零開始:Django項目的創建與配置指南 date: 2024/5/2 18:29:33 updated: 2024/5/2 18:29:33 categories: 後端開發 tags: Django WebDev Python ORM Security Deployment Op ...
  • 1、BOM對象 BOM:Broswer object model,即瀏覽器提供我們開發者在javascript用於操作瀏覽器的對象。 1.1、window對象 視窗方法 // BOM Browser object model 瀏覽器對象模型 // js中最大的一個對象.整個瀏覽器視窗出現的所有東西都 ...