You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js部署Netlify失败:无法加载linux-x64环境下的sharp模块

解决Netlify上Next.js项目sharp模块linux-x64运行时加载失败问题

问题背景

在Netlify部署Next.js项目时,触发构建流程遇到sharp模块无法在linux-x64运行时加载的错误,该模块用于API接口的图片压缩功能,无法移除。已配置netlify.toml但问题仍未解决:

当前netlify.toml配置

[context.staging]
  command = "yarn build"
  publish = ".next" 

[functions]
  node_bundler = "esbuild"
  external_node_modules = ["sharp"]
  included_files =  ["node_modules/sharp/**/*"]

[[plugins]]
  package = "@netlify/plugin-nextjs"

错误日志关键信息

Error: Could not load the "sharp" module using the linux-x64 runtime
Possible solutions:
- Ensure optional dependencies can be installed:
    npm install --include=optional sharp
    yarn add sharp --ignore-engines
- Ensure your package manager supports multi-platform installation:
    See https://sharp.pixelplumbing.com/install#cross-platform
- Add platform-specific dependencies:
    npm install --os=linux --cpu=x64 sharp
...
> Build error occurred
Error: Failed to collect page data for /api/image-process

解决方案

1. 构建前安装linux-x64平台的sharp依赖

sharp是原生模块,依赖对应平台的二进制文件,本地开发环境(如macOS/Windows)安装的版本无法在Netlify的Linux环境运行。修改构建命令,先安装适配linux-x64的sharp版本:

更新netlify.toml中的构建命令:

[context.staging]
  command = "yarn add sharp --ignore-engines --os=linux --cpu=x64 && yarn build"
  publish = ".next" 

2. 优化Netlify Functions配置

由于使用了@netlify/plugin-nextjs,需要确保Functions配置包含sharp的平台相关依赖文件,同时添加环境变量强制sharp使用本地安装的库:

更新netlify.toml:

[build.environment]
  SHARP_IGNORE_GLOBAL_LIBVIPS = "true"

[functions]
  node_bundler = "esbuild"
  external_node_modules = ["sharp"]
  included_files = ["node_modules/sharp/**/*", "node_modules/@img/sharp-linux-x64/**/*"]

[[plugins]]
  package = "@netlify/plugin-nextjs"

3. 清理Netlify构建缓存

Netlify的缓存可能保留了本地平台的sharp二进制文件,导致构建时复用错误版本:

  • 进入Netlify项目的Deploys页面
  • 点击右上角的Trigger deploy下拉菜单
  • 选择Clear cache and deploy site,重新触发构建

4. 匹配Node.js版本

确保Netlify使用的Node.js版本与sharp支持的版本一致,在netlify.toml中指定版本(以18.x为例,需根据sharp版本调整):

[build.environment]
  NODE_VERSION = "18"

内容的提问来源于stack exchange,提问作者MONEYMSN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 04:55:58