我正在尝试使用 @formatjs/intl-localematcher 将国际化添加到我的 next.js 项目中。我使用以下代码添加了一个配置文件:
// i18n.config.ts
export const i18n = {
defaultLocale: "en",
locales: ["en", "de", "fr"],
} as const;
export type Locale = (typeof i18n)["locales"][number];
然后,我添加了以下中间件:
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 {
const negotiatorHeaders: Record<string, string> = {};
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));
// @ts-ignore locales are readonly
const locales: string[] = i18n.locales;
const languages = new Negotiator({ headers: negotiatorHeaders }).languages();
const locale = matchLocale(languages, locales, i18n.defaultLocale);
return locale;
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
const pathnameIsMissingLocale = i18n.locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = getLocale(request);
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).*)"],
};
当我将项目部署到vercel时,在预览环境中出现以下错误:
RangeError: Incorrect locale information provided
at (node_modules/@formatjs/intl-localematcher/lib/abstract/CanonicalizeLocaleList.js:7:16)
at (node_modules/@formatjs/intl-localematcher/lib/index.js:8:34)
at (middleware.ts:18:4)
at (middleware.ts:30:19)
at (node_modules/next/dist/esm/server/web/adapter.js:163:22)
at (node_modules/next/dist/esm/server/async-storage/request-async-storage-wrapper.js:72:23)
at (node_modules/next/dist/esm/server/web/adapter.js:150:52)
错误似乎源自以下行:
const locale = matchLocale(languages, locales, i18n.defaultLocale);
但是,鉴于我提供了默认区域设置,我不明白为什么会出现上述错误。
遇到同样的问题。你修好了吗