8

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.

2 Answers2

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.

RH Becker
  • 1,692
  • 1
  • 14
  • 11
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

luisdemarchi
  • 1,402
  • 19
  • 29