我实现了支持多语言的next-intl.所以我的路径看起来像www.next.com/dewww.next.com/en

我用的是NextJS 14美元.

<NextLink href="/support-us">{t("About us")}</NextLink>

例如,当我想导航到/support-us时,它必须导航到/en/support-us,而不是我导航到/support-us,所以它会抛出错误.

NotFoundError:无法在"Node"上执行"removeChild":要执行的 node 被删除不是这个 node 的子 node .

这是我的代码. middleware.ts

import createMiddleware from "next-intl/middleware";
import { locales } from "./i18n";

export default createMiddleware({
  // A list of all locales that are supported
  locales,

  // Used when no locale matches
  defaultLocale: "en",
});

export const config = {
  // Match only internationalized pathnames
  matcher: ["/", "/(en|it|de|nl|fr|sv|es|nb|pt|pl)/:path*"],
};

i18next

import { notFound } from "next/navigation";
import { getRequestConfig } from "next-intl/server";

interface Language {
  symbol: string;
  name: string;
}

export const supportedLanguages: Language[] = [
  { symbol: "EN", name: "English" },
  { symbol: "DE", name: "Deutsch" },

];

const languageSymbolsLowercase: string[] = supportedLanguages.map((lang) =>
  lang.symbol.toLowerCase()
);

const initialLocales: string[] = [];

const combinedLocales: string[] = [
  ...initialLocales,
  ...languageSymbolsLowercase,
];

export const locales: string[] = combinedLocales;

export default getRequestConfig(async ({ locale }) => {
  if (!locales.includes(locale)) notFound();

  return {
    messages: (await import(`../messages/${locale}.json`)).default,
  };
});

推荐答案

At the end I had to add a navigation file as mentioned in the next-intl documentation in there it exports a Link component which solves the problem and navigates to /[locale]/support-us
for example /en/support-us here is my navigation file

import {
  createLocalizedPathnamesNavigation,
  Pathnames,
} from "next-intl/navigation";
import { locales } from "./i18n";

export const localePrefix = "always"; // Default

export const pathnames = {
  "/support-us": "/support-us",
} satisfies Pathnames<typeof locales>;

export const { Link, redirect, usePathname, useRouter, getPathname } =
  createLocalizedPathnamesNavigation({ locales, localePrefix, pathnames });

并使用导航文件中导出的Link

import { Link as NavLink } from "@navigation"
<NavLink href="/support-us">{t("support us")}</NavLink>

Typescript相关问答推荐

如何基于对象关键字派生类型?

如何使用属性作为具有Generics的TypScript类中的类型守护?

在配置对象上映射时,类型脚本不正确地推断函数参数

webpack错误:模块找不到.当使用我的其他库时,

如何通过TypeScript中的工厂函数将区分的联合映射到具体的类型(如类)?

状态更新后未触发特定元素的Reaction CSS转换

来自类型脚本中可选对象的关联联合类型

PrimeNG日历需要找到覆盖默认Enter键行为的方法

尽管对象的类型已声明,但未解析的变量<;变量

在保留类型的同时进行深层键名转换

在React中定义props 的不同方式.FunctionalComponent

类型脚本-在调用期间解析函数参数类型

TypeScrip-如何自动推断UNION变量的类型

如何为特定参数定义子路由?

打印脚本中正则函数和函数表达式的不同类型缩小行为

如何从上传文件中删除预览文件图标?

如何将通用接口的键正确设置为接口的键

使用Cypress测试从Reaction受控列表中删除项目

字符串文字联合的分布式条件类型

Typescript:是否将联合类型传递给重载函数?