How to debug in VS Code a local AWS Lambda function with API Gateway written in TypeScript?
I wrote a medium article explaining how to create, invoke and debug a TypeScript lambda function. Please for more details check the following link.
Requirements
- SAM CLI
- Docker
- Node
- Visual studio code
1- Create a nodejs12x;
Create a nodejs12x lambda;
Install TypeScript:
npm i -g typescript
Initialize typescript:
tsc --init
(It will create the tsconfig.json file)Replace the created tsconfig.json file with the following code:
{ "compilerOptions": { "module": "CommonJS", "target": "ES2017", "noImplicitAny": true, "preserveConstEnums": true, "outDir": "./built", "sourceMap": true }, "include": ["handler/**/*"], "exclude": ["node_modules", "**/*.spec.ts"] }
Delete app.js file;
Create your lambda in TypeScript code inside of handler folder (you need o create it):
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda"; export const lambdaHandler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { const queries = JSON.stringify(event.queryStringParameters); return { statusCode: 200, body: `Queries: ${queries}` } }
Adapt the template.yaml. Change the CodeUri path of your lambda:
CodeUri: hello-world/built
Install the needed node packages:
npm install typescript @types/aws-lambda @types/node -save-dev
Package json:
{ "name": "typescript_lambda", "version": "1.0.0", "description": "hello world sample for TypeScript", "main": "app.js", "repository": "https://github.com/jafreitas90/AWS", "author": "Jorge Freitas", "license": "JorgeFreitas Ltd :)", "dependencies": { }, "scripts": { "compile": "tsc" }, "devDependencies": { "@types/aws-lambda": "^8.10.71", "@types/node": "^14.14.22", "aws-sdk": "^2.815.0", "typescript": "^4.1.3" } }
npm install
npm run compile
Set a breakpoint in your lambda function (TypeScript code). On the left panel select Debug and then Start debugging (green button on top). And that's it :)
Please find more details in my tutorial.
source code