NextJS中withNextIntl与withPlaiceholder插件兼容问题及解决方案咨询
Next.js 14 嵌套使用 withNextIntl 与 withPlaiceholder 部署 Vercel 构建失败的解决方案
问题背景
使用最新版 Next.js 14,在 next.config.mjs 中通过嵌套方式组合 withNextIntl 和 withPlaiceholder 插件配置项目,但部署到 Vercel 时无法完成构建。目前已改用 Jimp 处理图片模糊效果并运行正常,希望了解该场景下的解决方案。
原配置代码如下:
import createNextIntlPlugin from "next-intl/plugin"; import withPlaiceholder from "@plaiceholder/next"; const withNextIntl = createNextIntlPlugin(); /** @type {import('next').NextConfig} */ const nextConfig = { images: { remotePatterns: [ { hostname: "firebasestorage.googleapis.com", }, { protocol: "https", hostname: "cdn.sanity.io", }, ], }, env: { POSTGRES_PRISMA_URL: process.env.POSTGRES_PRISMA_URL, POSTGRES_URL_NON_POOLING: process.env.POSTGRES_URL_NON_POOLING, }, }; export default withPlaiceholder(withNextIntl(nextConfig));
可能的原因
- 插件执行顺序冲突:嵌套调用时,后执行的插件可能覆盖或破坏先执行插件的配置,尤其是涉及构建流程钩子时。
- Vercel 环境依赖缺失:
@plaiceholder/next依赖 Sharp 处理图片,Vercel 默认环境可能未正确安装 Sharp 或存在版本兼容问题。 - 配置合并错误:两个插件对 NextConfig 的类型处理不一致,导致合并后出现无效字段触发构建报错。
解决方案
方案1:调整插件执行顺序
尝试交换嵌套顺序,确保配置合并逻辑正常:
import createNextIntlPlugin from "next-intl/plugin"; import withPlaiceholder from "@plaiceholder/next"; const withNextIntl = createNextIntlPlugin(); /** @type {import('next').NextConfig} */ const baseConfig = { images: { remotePatterns: [ { hostname: "firebasestorage.googleapis.com", }, { protocol: "https", hostname: "cdn.sanity.io", }, ], }, env: { POSTGRES_PRISMA_URL: process.env.POSTGRES_PRISMA_URL, POSTGRES_URL_NON_POOLING: process.env.POSTGRES_URL_NON_POOLING, }, }; // 先执行图片处理插件,再包裹国际化插件 export default withNextIntl(withPlaiceholder(baseConfig));
方案2:修复 Vercel 环境下的 Sharp 依赖
在项目根目录创建 vercel.json,指定 Sharp 二进制包的下载源:
{ "installCommand": "npm install --ignore-scripts=false --sharp_binary_host=https://github.com/lovell/sharp-libvips/releases/download/v8.15.1/ --sharp_libvips_binary_host=https://github.com/lovell/sharp-libvips/releases/download/v8.15.1/" }
同时在 package.json 中锁定 Sharp 版本(推荐与 @plaiceholder/next 依赖的版本匹配,比如 0.32.6)。
方案3:用插件组合工具统一管理
安装 next-compose-plugins 来避免嵌套冲突,统一管理多个插件:
- 安装依赖:
npm install next-compose-plugins
- 修改配置文件:
import createNextIntlPlugin from "next-intl/plugin"; import withPlaiceholder from "@plaiceholder/next"; import withPlugins from "next-compose-plugins"; const withNextIntl = createNextIntlPlugin(); /** @type {import('next').NextConfig} */ const baseConfig = { images: { remotePatterns: [ { hostname: "firebasestorage.googleapis.com", }, { protocol: "https", hostname: "cdn.sanity.io", }, ], }, env: { POSTGRES_PRISMA_URL: process.env.POSTGRES_PRISMA_URL, POSTGRES_URL_NON_POOLING: process.env.POSTGRES_URL_NON_POOLING, }, }; export default withPlugins([ [withPlaiceholder], [withNextIntl] ], baseConfig);
方案4:定位具体构建错误
登录 Vercel 控制台查看完整构建日志:
- 若为 Sharp 安装失败,按方案2处理;
- 若为配置字段冲突,对照两个插件的官方文档,移除重复或冲突的配置项;
- 若为路由与图片钩子冲突,在
next-intl配置中排除图片资源目录。
内容的提问来源于stack exchange,提问作者Xun Ruan
相关产品推荐
相关产品推荐

