添加next-intl后Next.js应用无法部署到GitHub Pages
Next.js + next-intl GitHub构建报错及客户端组件locale处理问题
报错信息
Injecting property=output and value=export in: import createNextIntlPlugin from 'next-intl/plugin'; const withNextIntl = createNextIntlPlugin(); /** @type {import('next').NextConfig} */ const nextConfig = {}; export default withNextIntl(nextConfig); Error: TypeError: error must be an instance of Error
配置代码
app/[locale]/layout.tsx:
import { Inter } from "next/font/google"; import "./globals.css"; import {NextIntlClientProvider} from 'next-intl'; import {getMessages} from 'next-intl/server'; import {unstable_setRequestLocale} from 'next-intl/server'; const locales = ['en', 'pt']; export function generateStaticParams() { return locales.map((locale) => ({locale})); } const inter = Inter({ subsets: ["latin"] }); export default async function RootLayout({ children, params: {locale}, }: Readonly<{ children: React.ReactNode; params:{ locale: string; } }>) { unstable_setRequestLocale(locale); const messages = await getMessages(); return ( <html lang={locale}> <body className={inter.className}> <NextIntlClientProvider locale={locale} messages={messages}> {children} </NextIntlClientProvider> </body> </html> ); }
问题背景
按next-intl文档配置静态渲染:在根布局添加generateStaticParams,并尝试在所有布局、页面调用unstable_setRequestLocale。但主页面app/[locale]/page.tsx是客户端组件(带"use client"),无法调用该服务端函数。本地构建正常,推送到GitHub触发上述错误。
解决方案
1. 排查版本兼容性
确保next-intl与Next.js版本匹配,比如Next.js 14对应next-intl@3.x及以上版本,版本不兼容易引发内部构建错误。
2. 调整next.config.js配置
错误提示涉及output属性注入冲突,按部署方式调整配置:
- 若为静态导出,显式声明输出模式:
import createNextIntlPlugin from 'next-intl/plugin'; const withNextIntl = createNextIntlPlugin(); const nextConfig = { output: 'export' }; export default withNextIntl(nextConfig);
- 若为Vercel/Serverless部署,移除
output配置,避免插件自动注入导致冲突。
3. 客户端组件无需调用unstable_setRequestLocale
unstable_setRequestLocale是服务端函数,仅需在服务端渲染的布局、页面中调用。客户端组件可通过useLocale()等next-intl钩子获取locale,无需额外调用该函数——根布局的NextIntlClientProvider已传递locale上下文。
4. 校验locale一致性
确保generateStaticParams返回的locale列表,与next-intl配置文件(如i18n.ts)中定义的locales完全一致,避免不匹配引发的渲染错误。
5. 清理构建缓存
GitHub Actions构建时可能存在缓存污染,在构建步骤添加缓存清理命令:
npm run clean # 需在package.json中配置"clean": "next clean"
内容的提问来源于stack exchange,提问作者Vitor Hugo Cunha
相关产品推荐
相关产品推荐

