When I use the aws-sdk
module Node.js 18.x:
const aws = require("aws-sdk");
exports.handler = async (event) => {
console.log('Hello!');
// some code
};
I got this error:
{
"errorType": "ReferenceError",
"errorMessage": "require is not defined in ES module scope, you can use import instead",
"trace": [
"ReferenceError: require is not defined in ES module scope, you can use import instead",
" at file:///var/task/index.mjs:1:13",
" at ModuleJob.run (node:internal/modules/esm/module_job:193:25)",
" at async Promise.all (index 0)",
" at async ESMLoader.import (node:internal/modules/esm/loader:530:24)",
" at async _tryAwaitImport (file:///var/runtime/index.mjs:921:16)",
" at async _tryRequire (file:///var/runtime/index.mjs:970:86)",
" at async _loadUserApp (file:///var/runtime/index.mjs:994:16)",
" at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1035:21)",
" at async start (file:///var/runtime/index.mjs:1200:23)",
" at async file:///var/runtime/index.mjs:1206:1"
]
}
The same code works fine with late versions for example Node.js 16.x
.
What is the reason of this error, and how can we avoid it.
2
Answers
Node18 for Lambda uses JavaScript SDK V3 .
AWS SDK for Javascript v2 publishes a single npm package that supports all the AWS services. This makes it easy to use multiple services in a project at the cost of a large dependency when only using a handful of services or operations.
In resource constrained environment such as mobile devices, having separate packages for each service client allows optimizing the dependency. The AWS SDK for Javascript v3 provides such modular packages. We have also split up the core parts of the SDK so that service clients only pull in what they need. For example, a service that sends responses in JSON will no longer need to also have an XML parser as a dependency.
As you only import modules that you need, you can do so like below:
const { S3 } = require("@aws-sdk/client-s3");
SDK V2
SDK V3
Backward V2 Compatibility Style
source
Indeed, "Node18 for Lambda uses JavaScript SDK V3" as @Lee Hannigan said
You can also use a v2 compatible style as describded in Amazon’s documentation :