CDK deployment of lambda functions does not currently support the importing of Typescript modules

I’m currently using CDK to develop my serverless application in AWS. However, I encountered an issue where the lambda function fails to import TypeScript modules as JavaScript modules post TS file compilation.

As a result, I am encountering a “Module not found” error when attempting to invoke my lambda function.

Here are the steps I follow before deploying the stack:

  1. tsc -> to compile TS files
  2. cdk synth
  3. cdk deploy

TypeScript configuration:

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "lib": [
      "es2018"
    ],
    "noEmit": false,
    "declaration": false,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "cdk.out"
  ]
}

Code snippet:

import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';
import { DynamoDBClient, GetItemCommand, GetItemCommandInput } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";

export async function handler(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
console.log('event', event);

let userLat = event.pathParameters?.lat;
let userLng = event.pathParameters?.lng;    
let tableName = process.env.TABLE_NAME;
let results;

const dbClient: DynamoDBClient = new DynamoDBClient({ region: "ap-south-1" });
let params: GetItemCommandInput;

if (tableName) {
     params = {
        TableName: tableName,
        Key: marshall({
          "lat": userLat, 
          "lng": userLng
        }),
      };
}

const run = async function () {
    try {
        const resp = await dbClient.send(new GetItemCommand(params));
        results = unmarshall(resp.Item || {});
    } catch(err) {
        results = err;
    }
};

run();

return {
    body: JSON.stringify(
        results
    ),
    statusCode: 200
};     }

Additional details:

  • Node: v14.20.0
  • NPM: 6.14.17
  • CDK: 2.40.0 (build 56ba2ab)
  • TypeScript Version: 4.8.2

Error Message:

{ "errorType": "Runtime.ImportModuleError", "errorMessage": "Error: Cannot find module '@aws-sdk/client-dynamodb'\nRequire stack:\n- /var/task/fetchpartner.js\n- /var/runtime/UserFunction.js\n- /var/runtime/Runtime.js\n- /var/runtime/index.js", "trace": [ "Runtime.ImportModuleError: Error: Cannot find module '@aws-sdk/client-dynamodb'", "Require stack:", "- /var/task/fetchpartner.js", "- /var/runtime/UserFunction.js", "- /var/runtime/Runtime.js", "- /var/runtime/index.js", " at _loadUserApp (/var/runtime/UserFunction.js:221:13)", " at Object.module.exports.load (/var/runtime/UserFunction.js:279:17)", " at Object. (/var/runtime/index.js:43:34)", " at Module._compile (internal/modules/cjs/loader.js:1085:14)", " at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)", " at Module.load (internal/modules/cjs/loader.js:950:32)", " at Function.Module._load (internal/modules/cjs/loader.js:790:12)", " at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)", " at internal/main/run_main_module.js:17:47" ] }

Answer №1

One option is to execute npm init within the directory housing your lambda code and proceed to install desired modules there. Alternatively, you could employ a tool like webpack to bundle your code and modules into a unified file.

Answer №2

To streamline the deployment process, consider utilizing the NodeJsFunction instead of the Lambda function. This will execute an esbuild within the directory prior to deployment.

Find more information here: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html

For code implementation details, refer to this link: https://github.com/schuettc/single-stack-full-stack-example/blob/9c5c3f51381a4c3d813ed097a298fccc16e81509/src/infrastructure.ts#L38-L51

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to pass a parameter dynamically in the get method?

When looking at the network tab, I realized that I sent the query '' Unfortunately, it didn't work as expected. How do I adjust the query to have the order like this: Should the 'q' parameter come after the search? getArtists(q ...

The value entered for creating a payment method is invalid: the card must be in the form of an object

I am in the process of setting up a payment method using the Next.js library from Stripe. Here is the code snippet: import React, { FunctionComponent } from 'react'; import type { DisplaySettingsProps } from '@company/frontoffice/types' ...

Using jasmine-node to create a spy on a constructor invoked within another function

As a beginner in Jasmine, I am looking to write unit tests for a node.js application using this framework. However, I am facing some challenges, one of which is described below: var sampleFunction = function(){ var loader = new Loader(params); // ...

What is the recommended method for writing JavaScript scripts with AJAX in a Rails application? How can URLs be incorporated into the script effectively?

When incorporating AJAX into my Rails application, I encounter difficulties when specifying the URL for the request within a script. While it is recommended to use helpers like my_resource_path instead of manually writing paths, these helpers do not functi ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

Is there a way to display points on each vertex of my geometry using React, three.js, and Three-React-fiber?

I'm trying to figure out how to utilize the pointsmaterial and points object within three-react-fiber. Currently, I have a custom geometry that I've imported from a .gltf file and I'm rendering it like this: <mesh castShadow recei ...

I am encountering an issue with a JS addition operator while working with node.js and fs library

I'm trying to modify my code so that when it adds 1 to certain numbers, the result is always double the original number. For example, adding 1 to 1 should give me 11, not 2. fs.readFile(`${dir}/warns/${mentioned.id}.txt`, 'utf8', ...

What is the best way to have an HTML radio button automatically display as selected upon loading if the stored value is "on"?

Utilizing Javascript alongside html: I am facing an issue where a list containing radio buttons is dynamically loaded based on stored data when the page launches. Despite the stored value of the radio being set to "on", the radio button does not show up a ...

Is there a way to generate a custom URL using Javascript from form inputs?

I am currently working on a form with a dropdown menu where users can select a name and have the affiliate code matched to it used in the URL. However, I encountered an issue with PHP changing periods to underscores. I am now exploring alternative solution ...

Struggling to retrieve a particular user using ExpressJs due to an error

Looking to retrieve a specific user in ExpressJS from a JSON file. Encountering this error message: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This is the snippet of code being u ...

Focus on selecting just one button within Angular

By retrieving values from a database and displaying them using ng-repeat within a div: <div ng-controller = "myTest"> <div ng-repeat="name in names"> <h4>{{name.name}}</h4> <button ng-class="{'active ...

The Holy Alliance of Laravel and Vue

I am facing issues with user authentication using Laravel Sanctum. I have set up everything properly, with Vite and Vue 3 as the frontend. The problem arises when I attempt to login with Laravel's default auth - it works fine. However, when I make a r ...

Iterating through a collection of objects, triggering a promise for each object and recording its completion

I have encountered a challenge where I need to iterate through an array of objects obtained from a promise, and for each object in the array, I must invoke another promise. After all these promises are executed, I want to display "DONE" on the console. Is ...

The file could not be located on the server during the project build and upload process

Presently, I'm engrossed in a project involving Angular 9 and ASP Core 3. You can find the website at: Nevertheless, encountering an error when trying to access this URL: http://mag-testcpl.astromap.ir/assets/vendors/global/toastr.css The culprit ...

Reversing ngModel modifications does not accurately display changes in the view

Presently, my table contains editable cells, with the functionality to undo changes to each cell. To achieve this, I initially created a duplicate of each object in the array. Upon initialization, I mapped the array to create a new array with old values s ...

``There seems to be a problem with navigating to a specific

I'm encountering an issue with this script // App.js ( shrink ) var controller = require('./controller'); app.get('/', controller.index); app.get('/home', controller.home); // /controller/index.js var meta = { ...

"Selecting an element through Drag/Drop will result in the element being

INQUIRY I've encountered an issue with a draggable element ($("#draggable")) that interacts with a checkbox ($('#checkable')). When the $('#draggable') is dragged onto a box ($('#droppable')), it checks $(&apos ...

Having difficulty grasping the concept of AngularJS Promises

As I deepen my understanding of AngularJS, I find myself faced with the challenge of adapting code examples to fit my own projects. In this particular example sourced from Urish, it is clear that the variable "promise" must encompass the necessary functio ...

I am confused about what my teacher wants me to do. Have I interpreted the task correctly?

I completed the assignment, but I'm still unclear if I have fully grasped my teacher's instructions. Can you provide some insight on this for me? I attempted to solve it using two arrays, a for-loop, and connecting a button with a function, and ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...