Reputation: 185
I have an AWS Lambda whose folder structure is this:
src-ts
│ app.js
│ package.json
│
└───
Inside of my Lambda's package.json I have my list of dependencies and type
set to module
.
I then have a Lambda layer whose folder structure is this
nodejs
│ node_modules
│ package.json
│ package-lock.json
└──────
My layers package.json is identical to the one inside of my Lambda.
When I attempt to run the lambda, I get a "Cannot find module '/opt/nodejs/node14/node_modules/@aws-sdk/credential-provider-node' imported from /var/task/src-ts/app.js",
error. I am assuming this error has something to do with my Lambdas local package.json.
I have attempted to change my imports to use /opt/nodejs/node14/node_modules/@aws-sdk/credential-provider-node'
and just /opt/@aws-sdk/credential-provider-node
, neither of these attempts were succesful.
I finally changed module
setting in my tsconfig.json
to commonjs
, redeployed my transpiled JS to the Lambda a different time, this time without a package.json inside, and my Lambda worked as expected.
Is there a way to have a package.json inside the same folder as the deployed Lambda and to use dependencies that are coming from an AWS Lambda Layer?
Thank you for the help!
Upvotes: 1
Views: 4382
Reputation: 46
I have used a setup like this with a package.json in both the lambda and the layer many times. The code in the lambda can import libraries from the layer's package.json the same way that it would if the dependency were listed in its own package.json.
So depending on whether you're using commonjs or modules, you would use
const aws = require("@aws-sdk/credential-provider-node");
or
import aws from "@aws-sdk/credential-provider-node";
You only need to use the /opt/... path when you are importing modules that you've defined inside files in the layer.
EDIT: I should also note that I have not tried listing the same dependency in both package.json files. I'm not sure if that would cause a conflict or not.
EDIT2: As I'm doing my own research to solve an issue, I've come across numerous reports of issues using ES modules in both lambda layers and AWS SDK in general. So since you've mentioned it worked when you switched to commonjs, this is likely the source of your problem. There are multiple potential workarounds mentioned in those Github issues.
Please see:
Cannot find package when using ES Module and Lambda Layer
make AWS SDK JS v2 and v3 available with ESM in AWS Lambda
Upvotes: 3