I'm using NodeJs(ES6) on AWS Lambda with node_module as AWS Layer and I want to publish a message on SNS.
The above code works perfectly with CommonJs syntax but using import syntax (ES6) facing an issue with aws-sdk/sns-client as this is commonsJS module.
Package.json
{
"name": "test",
"version": "1.0.0",
"dependencies": {
"@aws-sdk/client-sns": "^3.370.0",
},
"type": "module",
}
- My code same as mentioned in AWS Documentation.
- Node Modules added into nodejs directory and zipped it as a layer.
../lib/snsClient.js
created as mentioned in the documentation.- Tried with nodejs16.x, nodejs18.x and nodejs.20.x and mjs extension.
- Want to use ES6 due to some dependencies.
ERROR
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.\nCommonJS modules can always be imported via the default export, for example using:\n\nimport pkg from 'aws-sdk';\nconst { AWS } = pkg;\n",
"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"
]
}
Tried following as well,
import pkg from 'aws-sdk';
const { AWS } = pkg;
Thank you in advance.
var AWS = require("aws-sdk")
is a AWS SDK v2 thing. You currently are including the v3 version - you need to install v2 to get that to work. Otherwise, to use v3 you need to useimport { SNSClient } from "@aws-sdk/client-sns"
I recommend staying with v3 since v2 is really old. docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/…