'Cannot import package in AWS lambda with Nodejs14.x ES module

I have a layer where the path of node_modules is nodejs/node14/node_modules.

Using that layer, and I try to import a package in a Lambda function, say 'aws-cloudfront-sign', like this:

import cfsign from 'aws-cloudfront-sign'

I got error message

Cannot find package 'aws-cloudfront-sign' imported from /var/task/signer.js\nDid you mean to import aws-cloudfront-sign/lib/cloudfrontUtil.js?

But if I import the package like this:

import cfsign from '/opt/nodejs/node14/node_modules/aws-cloudfront-sign/lib/cloudfrontUtil.js'

It succeeds.

Do you know why? How could I import the package correctly?



Solution 1:[1]

This appears to be a bug. It is occurring with layers and the SDK. There are are a number of similar open issues on Github:

Nodejs Lambda: Cannot find package 'aws-sdk'

Cannot find package when using ES Module and Lambda Layer

ES6 imports don't work in @aws-sdk/client-iotsitewise

As you have worked out, the only workaround at present seems to be the use of absolute paths. E.g.:

import { DynamoDB } from 'aws-sdk;'

fails, whereas

import AWS from '/var/runtime/node_modules/aws-sdk/lib/aws.js';
const { DynamoDB } = AWS;

will work.

I suggest you add your voice to an existing open issue to help ensure it gets attention.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hendalst