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

使用Serverless+AWS JS v3 SDK时S3Client导入失败求助

问题描述

使用Serverless框架开发TypeScript的Serverless API,集成AWS JavaScript v3 SDK时,S3客户端本地调用出现模块找不到的错误,但相同逻辑的SNS客户端可正常运行。

环境与报错详情

  • package.json依赖:
"dependencies": {
    "@aws-sdk/client-s3": "^3.367.0",
    "@aws-sdk/client-sns": "^3.32.0",
  }
  • S3调用代码:
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'

const client = new S3Client({})

export const s3Upload = async (bucket: string, key: string, body: string) => {
  const command = new PutObjectCommand({
    Bucket: bucket,
    Key: key,
    Body: body,
  })

  const response = await client.send(command)
  console.log('s3 upload response', response)
  return response
}
  • 报错信息:
Error:
Webpack compilation failed:

in ../../node_modules/@aws-sdk/client-s3/dist-es/index.js 2:0-27
  Module not found: Error: Can't resolve './S3Client' in '/*/*/*/*/*/node_modules/@aws-sdk/client-s3/dist-es'

查看node_modules/@aws-sdk/client-s3/dist-es/index.js内容:

export * from "./S3";
export * from "./S3Client";
export * from "./commands";
export * from "./models";
export * from "./pagination";
export * from "./waiters";
export { S3ServiceException } from "./models/S3ServiceException";

解决方案

1. 统一AWS SDK v3版本并重装依赖

S3与SNS的SDK版本差异过大(3.367.0 vs 3.32.0),可能导致模块结构不兼容:

  • 修改package.json,将所有AWS SDK依赖统一为同一稳定版本:
"dependencies": {
    "@aws-sdk/client-s3": "^3.421.0",
    "@aws-sdk/client-sns": "^3.421.0"
  }
  • 删除旧依赖文件并重装:
rm -rf node_modules package-lock.json
npm install

2. 调整Serverless Webpack配置

默认Webpack配置可能存在ES模块解析问题,修改webpack.config.js:

module.exports = {
  // 原有配置...
  resolve: {
    extensions: ['.js', '.json', '.ts', '.tsx'],
    symlinks: false // 禁用符号链接解析,避免路径识别异常
  }
};

若使用serverless-webpack插件,确保插件配置中指定正确的包管理器(如packager: 'npm'),并关闭不必要的代码优化。

3. 清理Webpack缓存

本地调用时的缓存可能残留旧模块引用,执行:

sls invoke local --function <你的函数名> --no-webpack-cache

或手动删除缓存目录:

rm -rf .webpack

4. 检查依赖包完整性

若重装后仍报错,查看node_modules/@aws-sdk/client-s3/dist-es/目录下是否存在S3Client.js:

  • 若不存在,说明依赖安装不完整,清理npm缓存后重装:
npm cache clean --force
rm -rf node_modules package-lock.json
npm install

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 20:13:17