2

I added the knex module (for example) to my function lambda (Node.js 14.x) from a lambda layer. When I deploy my function in AWS Lambda and I use require in my lambda function works but with import not works.

Note: Locally works with require and import with modules installeds in node_modules in my lambda function.

require (It works)

index.js

const knex = require('knex')(myConfig);

package.json

{
  "name": "my-function",
  "version": "1.0.0",
  "main": "index.js",
  "dependencies": {}
}

import (Not works)

index.js

import knexModule from 'knex';

const {knex} = knexModule;
const db = knex(configKnex);

package.json

{
  "name": "my-function",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "dependencies": {}
}

Error

Response
{
  "errorType": "Error",
  "errorMessage": "Cannot find package 'knex' imported from /var/task/index.js\nDid you mean to import knex/knex.js?",
  "trace": [
    "Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'knex' imported from /var/task/index.js",
    "Did you mean to import knex/knex.js?",
    "    at new NodeError (internal/errors.js:322:7)",
    "    at packageResolve (internal/modules/esm/resolve.js:732:9)",
    "    at moduleResolve (internal/modules/esm/resolve.js:773:18)",
    "    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:887:11)",
    "    at Loader.resolve (internal/modules/esm/loader.js:89:40)",
    "    at Loader.getModuleJob (internal/modules/esm/loader.js:242:28)",
    "    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:76:40)",
    "    at link (internal/modules/esm/module_job.js:75:36)",
    "    at process.runNextTicks [as _tickCallback] (internal/process/task_queues.js:60:5)",
    "    at /var/runtime/deasync.js:23:15"
  ]
}

How can I use import in AWS Lambda?

My layer downloaded from AWS Lambda looks like this:

enter image description here

2
  • Does this help? Commented May 2, 2022 at 5:07
  • @ApoorvaChikara I followed the instructions but without success. Thanks. Commented May 4, 2022 at 23:54

1 Answer 1

1

This is because Lambda layers do not support ES modules yet, there are workarounds, however:

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.