Setting up a Severless project with Typescript

There are a couple of way to get Serverless functions working with Typescript. If you’re not like me, and you don’t mind a little bit of “magic” in your life, Graphcool’s excellent Typescript Plugin is a good bet.

My preference is not to have any “surprises” along the way — and therefore I’ve come up with a little more spartan, but a simple convention that requires little to no configuration with a bit more transparency.

1. Compile your Typescript to an distribution normally, as you’d do.

In this sense, your tsconfig.json might look like:

This will take all your .tsfiles in a src directory and create a corresponding compiled .js files in a lib directory.

example:

src/controllers/addUser.ts -> lib/controllers/addUser.js

src/handlers/heartbeat.ts -> lib/handlers/heartbeat.js

2. Call handlers in the lib folder directly from your serverless.yml

When you call your handlers for lambda endpoints, now you can just refer to compiled javascript files.

I personally like this approach because I have less surprises along the way. If something is not working due to a transformation/compilation glitch, I can just inspect the javascript in the lib directory. And what gets pushed — is what’s inside lib directory.

Before you do a serveless deploy, be sure to do a tsc beforehand to build the latest source. I have a variation of these as my package.json npm scripts to help me do this:

{
  "clean-build": "rm -rf lib",
  "build": "yarn clean-build && tsc",
  "watch": "yarn clean-build && tsc -w",
  "deploy": "yarn build && serverless deploy",
}

When I’m ready, I just do a yarn deploy instead of a serveless deploy now.

Written on August 8, 2017