Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 395
Šimon Kvasnička Avatar asked May 03 '26 06:05

Šimon Kvasnička


1 Answers

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.

like image 100
RH Becker Avatar answered May 04 '26 19:05

RH Becker