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

AWS Lambda+Layer环境下Node.js ES6导入aws-sdk模块报错问题

AWS Lambda ES6导入AWS SDK模块报错解决方案

问题背景

在AWS Lambda中使用Node.js(ES6语法),将node_modules打包为AWS Layer实现依赖管理,需向SNS发布消息。使用CommonJS语法时代码运行正常,但切换到ES6的import语法后,因模块导入方式问题报错。

当前package.json配置:

{
  "name": "test",
  "version": "1.0.0",
  "dependencies": {
    "@aws-sdk/client-sns": "^3.370.0"
  },
  "type": "module"
}

相关情况:

  • 代码与AWS官方文档示例一致
  • Node Modules已放入nodejs目录并打包为Layer
  • 已按文档创建../lib/snsClient.js
  • 测试过nodejs16.x、nodejs18.x、nodejs20.x版本及.mjs扩展名
  • 因业务依赖必须使用ES6语法

报错信息

2024-05-05T20:50:31.064Z    undefined   ERROR   Uncaught Exception  
{
    "errorType": "Runtime.UserCodeSyntaxError",
    "errorMessage": "SyntaxError: Named export 'AWS' not found. The requested module 'aws-sdk' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'aws-sdk';
const { AWS } = pkg;
",
    "stack": [
        "Runtime.UserCodeSyntaxError: SyntaxError: Named export 'AWS' not found. The requested module 'aws-sdk' is a CommonJS module, which may not support all module.exports as named exports.",
        "CommonJS modules can always be imported via the default export, for example using:",
        "",
        "import pkg from 'aws-sdk';",
        "const { AWS } = pkg;",
        "",
        "    at _loadUserApp (file:///var/runtime/index.mjs:1084:17)",
        "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
        "    at async start (file:///var/runtime/index.mjs:1282:23)",
        "    at async file:///var/runtime/index.mjs:1288:1"
    ]
}

已尝试的无效方案

尝试过以下导入方式,问题仍未解决:

import pkg from 'aws-sdk'; 
const { AWS } = pkg;

核心原因与解决方案

核心原因

你的package.json中依赖的是AWS SDK v3的@aws-sdk/client-sns,但代码中却在导入AWS SDK v2的aws-sdk模块。两者的导入逻辑完全不同,且v2的aws-sdk是CommonJS模块,在ES6模块环境下无法按v2的方式导入。

正确解决方案

  1. 修正模块导入逻辑,使用AWS SDK v3的ES6语法导入对应模块:

    • 编辑../lib/snsClient.js,创建SNS客户端:
      import { SNSClient } from "@aws-sdk/client-sns";
      // 替换为你的AWS区域
      const snsClient = new SNSClient({ region: "us-east-1" });
      export default snsClient;
      
    • Lambda主函数中导入客户端与发布命令:
      import { PublishCommand } from "@aws-sdk/client-sns";
      import snsClient from "./lib/snsClient.js";
      
      export const handler = async (event) => {
        const publishParams = {
          Message: "测试SNS消息内容",
          TopicArn: "arn:aws:sns:us-east-1:123456789012:your-topic-name"
        };
      
        try {
          const response = await snsClient.send(new PublishCommand(publishParams));
          return {
            statusCode: 200,
            body: JSON.stringify({ messageId: response.MessageId })
          };
        } catch (error) {
          console.error("发布SNS消息失败:", error);
          return {
            statusCode: 500,
            body: JSON.stringify({ error: error.message })
          };
        }
      };
      
  2. 确认Layer结构正确性:
    打包Layer时,确保node_modules放在nodejs目录下,最终结构为:

    nodejs/
      node_modules/
        @aws-sdk/
          client-sns/
    
  3. 保持package.json配置:
    保留"type": "module"配置,确保Node.js以ES6模块方式解析代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 08:50:58