AWS Lambdas give us quick code running in the cloud, but we don’t have to know how it is hosted. We are purely just writing functions running in the cloud. And with AWS CodeStar, getting a Node.js/Express.js Lambda set up and running has never been easier.
This all seems great, but it does come with a couple of issues. First, developers often need the ability to debug code locally. Second, having developers share resources is almost always going to result in some amount of pain; developers shouldn’t share resources. Third, the default template is JS only; it doesn’t use TypeScript.
In this blog post we are going to do two things:
- Set up a project so we can debug the AWS Lambda locally using VS Code
- Set up a project to use TypeScript with our code
Let’s get started.
We can take a couple of approaches to enable debugging for our AWS Lambda. We could debug the AWS Lambda locally, or we could take the easy way by debugging the Express.js application. The latter approach is the one we’ll take in this blog post.
We start this project as we would any other Express.js application: we just run the app.
But that won’t work with this AWS Lambda application. The app.js file doesn’t include the app.listen() call you might be expecting. So let’s add a new JS file, which I will name expressit.js. This helper file hosts the Express.js app on port 3000.
Now we can run our AWS Lambda as an Express application. But what about TypeScript?
Getting TypeScript set up is a little more work. First, we are going to have to do some npm installs.
npm install --save-dev typescript npm install --save-dev tslint
After we do that, we will need to set up our TypeScript tsconfig file. There are a lot of options we could do here, but for right now are going to keep it simple. Also, we are going to build our TypeScript files into JS files, and put the outputs in the dist folder.
Because we are using TypeScript, we will need to add a TypeScript version of the app.js file.
We will also need to update our expressit.js file to use the compiled version in the dist folder.
Now we need to get our build (TypeScript) set up and run the project with debugging.
The easiest way is to just let VS Code create a launch configuration for you. If you create a Node.js preview run configuration, there is a good chance it will have everything configured for you out of the box.