How to make ES modules import from a Lambda layer work?
Asked Answered
L

3

9

I have a lambda function in node v14 that imports AWS SDK v3 from a lambda layer.

In my function I can use my node modules from the layer only if I use CommonJS syntax:

const { parseUrl } = require('@aws-sdk/url-parser');

Using ES modules doesn't work.

import { parseUrl } from '@aws-sdk/url-parser';

It will throw an error: "errorMessage": "Cannot find package '@aws-sdk/url-parser' imported from /var/task/index.js\nDid you mean to import @aws-sdk/url-parser/dist-cjs/index.js?"

It should work. I have "type": "module" in package.json and locally the import works. It also starts working when I specify the full path to cjs index file:

import { parseUrl } from '/opt/nodejs/node_modules/@aws-sdk/url-parser/dist-cjs/index.js';

Which is really weird.

I checked NODE_PATH and /opt/nodejs/node_modules is there so I don't know where the problem is.

The full implementation is here so you can replicate the error: https://github.com/simon-q/lambda-layer-es-modules-error

Is it something broken in lambda layers or am I doing something wrong? I would really appreciate any help.

Thanks.

Lizzielizzy answered 1/3, 2022 at 20:41 Comment(3)
Found this tweet about the bug twitter.com/coderbyheart/status/…Elohist
Have a look at this github github.com/vibe/aws-esm-modules-layer-supportElohist
Thanks, Vive's github post save the day after hours spinning around this bug.Westerly
G
3

This doesn't help if you're stuck on an older runtime version, but as announced in this November 2022 blog post, the Node.js 18.x runtime introduces support for ES module resolution using NODE_PATH.

Galactic answered 23/3, 2023 at 2:25 Comment(1)
What is the best practice to maintain a AWS lambda function using ESM that has NPM deps, on local dev maintain (including file structure and bundle solution) and AWS deployment (using Lambda Layer or set NODE_PATH?)Statistics
G
0

it's a path error for files in node_modules folder. In this link you can get more details about the problem.

I created a serverless plugin that fixes it automatically, hope it helps someone. Follow the link: https://www.npmjs.com/serverless-esm-layer

Gaziantep answered 18/9, 2022 at 11:19 Comment(0)
S
0

https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html helped me out

I packaged my ESM dependencies in the following file structure before zipping + publishing

nodejs/node20/node_modules - where nodejs20.x is the compatible runtime set on the lambda

I then associate the layer with the lambda function in my build script (using github actions) and all seems to work now

Sarad answered 31/7 at 20:19 Comment(1)
What's the issue then?Statistics

© 2022 - 2024 — McMap. All rights reserved.