国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

next.js app目錄 i18n國際化簡單實(shí)現(xiàn)

這篇具有很好參考價(jià)值的文章主要介紹了next.js app目錄 i18n國際化簡單實(shí)現(xiàn)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

最近在用next寫一個(gè)多語言的項(xiàng)目,找了好久沒找到簡單實(shí)現(xiàn)的教程,實(shí)踐起來感覺都比較復(fù)雜,最后終于是在官方文檔找到了,結(jié)合網(wǎng)上找到的代碼demo,終于實(shí)現(xiàn)了,在這里簡單總結(jié)一下。

此教程適用于比較簡單的項(xiàng)目實(shí)現(xiàn),如果你是剛?cè)腴Tnext,并且不想用太復(fù)雜的方式去實(shí)現(xiàn)一個(gè)多語言項(xiàng)目,那么這個(gè)教程就挺適合你的。

此教程適用于app目錄的next項(xiàng)目。

先貼一下參閱的連接:

官方教程: next i18n 文檔

可參閱的代碼demo

實(shí)現(xiàn)思路

結(jié)合文件結(jié)構(gòu)解說一下大致邏輯:

next.js app目錄 i18n國際化簡單實(shí)現(xiàn)

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

大致思路是這樣,下面貼對(duì)應(yīng)的代碼。

/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,需要先安裝兩個(gè)依賴,這兩個(gè)依賴用于判斷用戶常用的語言:

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下的因項(xiàng)目而異,可以看個(gè)參考:
next.js app目錄 i18n國際化簡單實(shí)現(xiàn)

文件以語言簡寫命名,/i18n-config.ts里的locales有什么語言,這里就有多少個(gè)對(duì)應(yīng)的文件就行了。

/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();

實(shí)際使用可以做個(gè)參考:
next.js app目錄 i18n國際化簡單實(shí)現(xiàn)

到這里其實(shí)就實(shí)現(xiàn)了,但是下面的事情需要注意:

如果你的項(xiàng)目有集成了第三方需要配知道m(xù)iddleware的地方,比如clerk,需要調(diào)試一下是否沖突。

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

Clerk適配

clerk是一個(gè)可以快速登錄的第三方庫,用這個(gè)庫可以快速實(shí)現(xiàn)用戶登錄的邏輯,包括Google、GitHub、郵箱等的登錄。

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

就是這里沖突了,因?yàn)槲覀儗?shí)現(xiàn)多語言的邏輯是,用戶訪問localhost:3000的時(shí)候判斷用戶常用的語言,從而實(shí)現(xiàn)跳轉(zhuǎn)到localhost:3000/zh這樣。

這兩者實(shí)現(xiàn)都在middleware.ts文件中,上面這種配置會(huì)有沖突,這兩者只有一個(gè)能正常跑通,而我們想要的效果是兩者都能跑通,既能自動(dòng)跳轉(zhuǎn)到登錄頁面,也能自動(dòng)跳轉(zhuǎn)到常用語言頁面。

技術(shù)問題定位:這是因?yàn)槟阒貙懥薽iddleware方法,導(dǎo)致不會(huì)執(zhí)行Clerk的authMiddleware方法,視覺效果上,就是多語言導(dǎo)致了Clerk不會(huì)自動(dòng)跳轉(zhuǎn)登錄。

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

next.js app目錄 i18n國際化簡單實(shí)現(xiàn)

所以現(xiàn)在/middleware.ts文件內(nèi)的內(nèi)容變成了:

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了,大功告成。文章來源地址http://www.zghlxwxcb.cn/news/detail-855083.html

到了這里,關(guān)于next.js app目錄 i18n國際化簡單實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 【angular】實(shí)現(xiàn)簡單的angular國際化(i18n)

    【angular】實(shí)現(xiàn)簡單的angular國際化(i18n)

    實(shí)現(xiàn)簡單的angular國際化。本博客實(shí)現(xiàn)中文版和法語版。 將 Hello i18n! 變?yōu)?中文版:你好 i18n! 或 法語版:Bonjour l’i18n ! 。 創(chuàng)建一個(gè)項(xiàng)目: 在集成終端中打開。 添加本地化包: 在html中添加格式化標(biāo)識(shí): 現(xiàn)在運(yùn)行一下,頁面是: 生成翻譯模板語言包: 生成了一個(gè)文件夾: l

    2024年02月08日
    瀏覽(32)
  • spring6-國際化:i18n | 數(shù)據(jù)校驗(yàn):Validation

    spring6-國際化:i18n | 數(shù)據(jù)校驗(yàn):Validation

    1.1、i18n概述 國際化也稱作i18n,其來源是英文單詞 internationalization的首末字符i和n,18為中間的字符數(shù)。由于軟件發(fā)行可能面向多個(gè)國家,對(duì)于不同國家的用戶,軟件顯示不同語言的過程就是國際化。通常來講,軟件中的國際化是通過配置文件來實(shí)現(xiàn)的,假設(shè)要支撐兩種語言,

    2024年02月08日
    瀏覽(25)
  • 微信小程序-切換語言(國際化i18n)的方法封裝

    微信小程序-切換語言(國際化i18n)的方法封裝

    最近做的一個(gè)小程序的項(xiàng)目, 涉及到了 多語言的切換 , 就想到了之前vue用的多語言插件i18n, 就嘗試著在微信開放社區(qū)搜了一下, 沒有具體的實(shí)現(xiàn), 但是提供了大致的實(shí)現(xiàn)思路, 如下: 又結(jié)合了很多大佬的分享經(jīng)驗(yàn), 試著去封裝了一個(gè)微信的i18n方法 首先, 我們需要明確一下需要實(shí)

    2024年02月05日
    瀏覽(21)
  • 如何在Vue3中配置國際化語言i18n

    1. 安裝 vue-i18n 2. 創(chuàng)建一個(gè)i8n的配置文件 如:i18nConfig.js 3. 新建語言文件 zh-CN.js 和 en-US.js zh-CN.js 文件 en-US.js 文件 CONFIG.js 文件 4. 在 main.js 里面全局配置 通過上面四步即可配置完畢 下面說一下如何使用,分三種情況 在 .vue 組件中的 template 使用 在 .vue 組件中的 script 中使用 在

    2024年02月09日
    瀏覽(23)
  • SpringBoot 國際化(i18n) 支持中文鍵(KEY)的解決方法

    前言: 項(xiàng)目中要解決“中英文”切換的問題,想法是輸入key例如“你好”,然后去國際化文件找對(duì)應(yīng)的中文key,然后進(jìn)行輸出,如果沒有定義這個(gè)key,則輸出“你好”。但是中文key在properties文件中會(huì)已unicode編碼輸出,使用中文key時(shí)獲取不到對(duì)應(yīng)的value。 解決方法: 重構(gòu)$.

    2024年02月16日
    瀏覽(30)
  • 用i18n 實(shí)現(xiàn)vue2+element UI的國際化多語言切換詳細(xì)步驟及代碼

    用i18n 實(shí)現(xiàn)vue2+element UI的國際化多語言切換詳細(xì)步驟及代碼

    這個(gè)地方要注意自己的vue版本和i1n8的匹配程度,如果是vue2點(diǎn)幾,記得安裝i18n的@8版本,不然會(huì)自動(dòng)安裝的最新版本,后面會(huì)報(bào)錯(cuò)哦,查詢了下資料,好像最新版本是適配的vue3。 在src下面新建i18n文件夾,然后在里面新建index.js,里面的內(nèi)容如下 新建i18n文件夾里面新建config文

    2024年02月14日
    瀏覽(32)
  • Vue3中,國際化插件vue-i18n使用記錄,配合VSCode自動(dòng)化翻譯插件i18n Ally

    Vue3中,國際化插件vue-i18n使用記錄,配合VSCode自動(dòng)化翻譯插件i18n Ally

    說明文檔: vue-i18n 版本說明: vue: 3.0.0+ vue-i18n: 9.x版 src 目錄下新建目錄 lang ,存放 i18n 的配置。 新建目錄名稱: lang (語言)、 locales (語系設(shè)定)、 i18n ,這些名稱都可被VSCode圖標(biāo)插件( vscode-icons )檢測到并美化。 lang 目錄下,新建 index.js 文件,引入 vue-i18n 。 語言的配置信

    2024年02月12日
    瀏覽(26)
  • 用i18next使你的應(yīng)用國際化-React

    用i18next使你的應(yīng)用國際化-React

    ref: https://www.i18next.com/ i18next是一個(gè)用JavaScript編寫的國際化框架。 i18next為您提供了一個(gè)完整的解決方案,本地化您的產(chǎn)品從web端到移動(dòng)端和桌面端。 在react項(xiàng)目中安 i18next 依賴: i18next react-i18next i18next-browser-languagedetector,用于檢測用戶語言 創(chuàng)建 i18n.js 文件: 在 index.js 中導(dǎo)

    2024年02月15日
    瀏覽(25)
  • React18.x + i18next + antd 國際化正確使用姿勢及避坑指南

    React18.x + i18next + antd 國際化正確使用姿勢及避坑指南

    如果你使用這個(gè)教程還不能夠解決你的問題的話,直接私信我,免費(fèi)一對(duì)一給你解決。 具體的創(chuàng)建方法大家參考vite官方文檔,大概的操作如下,如果需要更詳細(xì)的,大家去自行搜索即可 因?yàn)槲疫@里使用的是ts版本,所以,你自己看著辦吧。 其中 i18next-browser-languagedetector i1

    2024年02月05日
    瀏覽(30)
  • Next實(shí)現(xiàn) i18n 傳遞 locales 給 getStaticPaths

    在 Next.js 中實(shí)現(xiàn)國際化( i18n )時(shí),可以通過配置 next.config.js 文件來傳遞 locales 給 getStaticPaths 函數(shù)。下面是一個(gè)示例代碼,演示如何在 next.config.js 中配置 locales ,并在 getStaticPaths 中獲取并使用這些 locales : 1、配置 next.config.js 文件: 2、在頁面組件中使用 getStaticPaths : 在

    2024年04月24日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包