如何在AWS Lambda函数中使用Sharp?调用时持续报错(Node.js图片缩放)
问题重现
为Lambda函数添加了一个包含Node.js Sharp图像处理库的Lambda Layer,执行以下代码时:
import sharp from 'sharp'; ... await sharp(inputImagePath) .resize(desiredWidth, desiredHeight) .toFile(outputImagePath);
收到错误:
{
"errorType": "Error",
"errorMessage": "Could not load the "sharp" module using the linux-x64 runtime\nPossible solutions:\n- Ensure optional dependencies can be installed:\n npm install --include=optional sharp\n yarn add sharp --ignore-engines\n- Ensure your package manager supports multi-platform installation:\n See https://sharp.pixelplumbing.com/install#cross-platform\n- Add platform-specific dependencies:\n npm install --os=linux --cpu=x64 sharp\n- Consult the installation documentation:\n See https://sharp.pixelplumbing.com/install",
"trace": [
"Error: Could not load the "sharp" module using the linux-x64 runtime",
...(省略部分栈信息)
]
}
不添加导入语句则会报sharp is undefined错误。
问题原因分析
这类报错通常由以下几种情况导致:
- Lambda函数的Node.js版本与Layer构建时使用的Node.js版本不兼容
- Layer未正确关联到Lambda函数,或部署区域与函数不一致
- 本地代码包中自行安装了Sharp,与Layer中的版本产生冲突
- Layer中的Sharp未针对Lambda的Linux x64环境正确编译
解决步骤
1. 核对Node.js版本一致性
Lambda运行时的Node.js版本必须与Layer构建时使用的版本完全匹配。比如Layer是基于Node.js 18.x构建的,函数就不能选择Node.js 20.x运行时。可以查看Layer的文档或构建记录确认版本,再调整Lambda函数的运行时版本。
2. 确认Layer的关联与部署状态
- 检查Lambda函数的Layers配置项,确认目标Layer已被添加
- 确保Layer部署在与Lambda函数相同的AWS区域
- 查看Layer的版本详情,确认包内文件结构正确,
/opt/nodejs/node_modules/sharp目录存在且包含完整的库文件
3. 移除本地代码包中的Sharp依赖
如果你的Lambda代码包中自行安装了Sharp,会和Layer中的库产生冲突。执行以下操作:
- 删除本地项目的
node_modules/sharp目录 - 修改
package.json,移除sharp依赖(如果存在) - 重新打包代码,确保最终的部署包中不包含Sharp相关文件
4. 手动构建适配Lambda环境的Layer(若上述方法无效)
如果公开Layer存在环境适配问题,可以自行构建:
- 使用Docker模拟Lambda的运行环境(Amazon Linux 2):
docker run -v "$PWD":/var/task public.ecr.aws/sam/build-nodejs18.x:latest /bin/bash - 在容器内安装Sharp:
npm install sharp --platform=linux --arch=x64 --libc=glibc - 将
node_modules目录打包成zip文件:zip -r sharp-layer.zip node_modules/ - 将zip文件上传为新的Lambda Layer,并关联到你的函数
内容的提问来源于stack exchange,提问作者king_anton

