I am trying to use import statements instead of require statements in my AWS Lambda project.
I need to import functionalities from the AWS SDK (which should be plausible when using the v3, as stated on the documentation).
To do so, I uploaded the dependency (@aws-sdk/client-sqs) as a Lambda layer, with the following tree structure:
.
└── nodejs
├── node_modules
│ ├── @aws-crypto
│ ├── @aws-sdk
│ ├── bowser
│ ├── entities
│ ├── fast-xml-parser
│ ├── tslib
│ └── uuid
├── package-lock.json
└── package.json
Back in the Lambda function, the following code (index.js) runs with no issues:
const { SQSClient, AddPermissionCommand } = require("@aws-sdk/client-sqs");
const handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
module.exports = {
handler,
}
But, as I stated in the beginning, I want to instead use import/export statements, so I replaced it with the following code:
import { SQSClient, AddPermissionCommand } from "@aws-sdk/client-sqs";
const handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
export {
handler,
}
I also created a package.json with the "type": "module" entry, located on the same folder as index.js:
{
"name": "test_es6",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
However, when testing the function it fails, with the following error message:
"Cannot find package '@aws-sdk/client-sqs' imported from /var/task/index.js Did you mean to import @aws-sdk/client-sqs/dist-cjs/index.js?"
I tried changing the import line to:
import { SQSClient, AddPermissionCommand } from "@aws-sdk/client-sqs/dist-cjs/index.js";
but it had no effect, resulting in the same error.
So, I guess I must be doing something wrong? Has anyone faced this issue when using AWS Lambda Layers? Thanks!