Steps to trigger a .ts file execution in AWS Lambda upon deployment

I'm encountering an issue with a lambda function written in TypeScript. While it works fine locally using sls invoke local -f main, I get an error when deploying and running it in the AWS console through a test function:

{
  "errorType": "Runtime.ImportModuleError",
  "errorMessage": "Error: Cannot find module 'handler'\nRequire stack:\n- /var/runtime/index.mjs",
  "trace": [
    "Runtime.ImportModuleError: Error: Cannot find module 'handler'",
    "Require stack:",
    "- /var/runtime/index.mjs",
    "    at _loadUserApp (file:///var/runtime/index.mjs:951:17)",
    "    at async Object.UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:976:21)",
    "    at async start (file:///var/runtime/index.mjs:1137:23)",
    "    at async file:///var/runtime/index.mjs:1143:1"
  ]
}

serverless.ts

import type { AWS } from "@serverless/typescript";

const serverlessConfiguration: AWS = {
    service: "email-service",
    frameworkVersion: "3",
    plugins: [],
    useDotenv: true,
    provider: {
        name: "aws",
        region: "us-east-2",
        runtime: "nodejs16.x",
        apiGateway: {
            minimumCompressionSize: 1024,
            shouldStartNameWithService: true,
        },
        environment: {
            AWS_NODEJS_CONNECTION_REUSE_ENABLED: "1",
            NODE_OPTIONS: "--enable-source-maps --stack-trace-limit=1000",
            FROM_EMAIL: process.env.FROM_EMAIL,
            SENDGRID_API_KEY: process.env.SENDGRID_API_KEY,
        },
    },
    // import the function via paths
    functions: {
        main: {
            handler: "handler.main",
            timeout: 60,
        },
    },
    package: { individually: true },
};

module.exports = serverlessConfiguration;

The file handler.ts does exist, and there is an exported function named main.

hanlder.ts

import SendEmail from "./src/sendemail";
import { ValidateInput } from "./src/validator";

export const main = async (event, _context) => {
    try {
        const errors = await ValidateInput(event);
        if (errors.length > 0) {
            return { statusCode: 400, body: { errors: errors } };
        }

        const result = await SendEmail(event);
        return { statusCode: 200, body: { data: result } };
    } catch (err) {
        return { statusCode: 500, body: { errors: [err.stack] } };
    }
};

Question: Can AWS Lambda run .ts files or do they need to be converted to js using tools like serverless-esbuild?

Answer №1

Node.js does not directly support TypeScript code execution. To run TypeScript code, it needs to be transpiled into JavaScript first. documentation

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 ensure an observable has finished before retrieving a value?

Looking at the function provided below: public getAssemblyTree(id: number) { .... const request = from(fetch(targetUrl.toString(), { headers: { 'responseType': 'json' }, method: 'GET' })); request.sub ...

Issue encountered with `vite:react-babel` due to an error related to the return type `ReturnType<typeof GenericConsumer<T>>` in Typescript

I am currently working on an application using Vite, React, and TypeScript. I have come across a piece of code that is causing Vite to fail: export type UseSearchFilters<T> = ReturnType<typeof useSearchFilters<T>> This is resulting in th ...

What purpose does the "dom" serve in the "lib" array found in the tsconfig.json configuration file of an

Within my Angular 6 project, I encountered the following segment in tsconfig.json and ts.config.spec.json: "lib": [ "es2016", "dom" ] I am curious about the role of dom. The official documentation explains: "... you can exclude declarati ...

The function is missing a closing return statement and the return type does not specify 'undefined'

It seems like the function lacks an ending return statement and the return type does not include 'undefined'. In a recent refactoring of the async await function called getMarkets, I noticed that I had mistakenly set the return type as Promise: ...

Toggle the visibility of a dropdown menu based on the checkbox being checked or unchecked

One challenge I am facing involves displaying and hiding DropDown/Select fields based on the state of a Checkbox. When the checkbox is checked, the Dropdown should be visible, and when unchecked, it should hide. Below is the code snippet for this component ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

Issues with the "noImplicitAny" setting in TS compilation

Having the following code snippet: let z; z = 50; z = 'z'; paired with the configuration in my tsconfig.json file: { "compilerOptions": { "target": "es5", "module": "commonjs", "sourceMap": false, "noEmitOnError": true, " ...

Leveraging gulp to enhance the module namespace in the TypeScript output of various files

I faced an issue when using the methodology of one file - one class in a TypeScript project, as shown in the example below. File Greeter.ts module App { export class Greeter { constructor(public greeting: string) { } public greet() { ...

Issue of false positive with no-shadow when defining a TypeScript enum within a JHipster application

How can I effectively use an enum in my application? export const enum typeEnum { TVY = 'TVY', USER = 'USER', } During the npm run webpack:build process, I encountered the following error : 12:111 error 'typeEnum' is ...

No error was flagged when the function had the potential to return undefined

getStage may sometimes return undefined without reporting any errors, which could potentially lead to a code crash. const a = Math.random() > 0.4 function getStage(): string { if(a) { return '' } } c ...

The model does not align with the body request, yet it is somehow still operational

My programming concept: class User { username: string; password: string; } Implementation of my function: const userList = []; function addUser(newUser: User) { userList.push(newUser); } Integration with Express router: router.post('/user ...

Developing a function that determines its return type based on the presence of an optional parameter

Let's explore a JavaScript function and its usage: const fooHandler = function(state, foo) { if (foo) { return {...state, foo} } else { return state.foo } } const currentState = {foo: 'foo', other: 'data'}; fooHandle ...

Prevent external scrolling while Bootstrap modal is active

<div class="modal mt-5p" role="dialog" [ngStyle]="{'display':IONotes}"> <div class="modal-dialog modal-md mt-0px width-70p"> <div class="modal-content" style="height:500 ...

Creating a custom object from a string enum: a step-by-step guide

For instance: enum App { App1 = "my-app1", App2 = "my-app2", } const AppPaths: { [ App.App1 ]: string; [ App.App2 ]: string; } = { [ App.App1 ]: "/some/path/to/app1", [ App.App2 ]: "/some/path/to/app2", ...

There was an unhandled rejection error stating: "TypeError - Unable to access property 'push' as it is undefined"

I am encountering an issue while trying to create a function that returns all indexes of an array. I'm not sure what mistake I might be making, as I keep getting an error stating that push cannot be used due to an undefined value. Here's the cod ...

Passing Parent Method to Child Component in React Native

I'm experiencing an issue trying to pass a method from my parent component to a child component. Although I believe my code is correct, I keep getting the error message undefined is not an object(evaluating '_this2.props.updateData'). Despit ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...

What is the best way to determine the highest value?

How can I ensure that the data is displayed based on the condition c.date <= this.selectedReport.report_date? The current code snippet if (Math.max(...this.costs.map(c => c.date))){} seems to be causing an issue where no data is being displayed. What ...

Extending a generic typed class in Typescript allows for the creation of

I am interested in extending the following class: import 'reflect-metadata'; import { IRepository, IFireOrmQueryLine, IOrderByParams, IEntity } from './types'; import { AbstractFirestoreRepository } from './AbstractFirestoreReposit ...

Unauthorized Access: Azure Web App and Typescript - "Access to this directory or page is restricted."

After developing a NodeJS server in Typescript, I attempted to deploy it to an Azure Web App through VS19. While the project functions correctly internally, when published to Azure, I encountered permission issues. The project was built using the "Basic A ...