How to create an OpenJS Architect serverless app with TypeScript

Brian Leroux’s avatar

by Brian Leroux
@brianleroux
on

Express train

In this article we’ll set up an Architect project that uses TypeScript to compile code for AWS Lambda.

Other articles in this series you may be interested in:


Let’s get started! First, let’s create a new Architect project:

npm init @architect ./myTSapp

The init script generates a new, single Lambda function in src/http/get-index/index.js which we’ll overwrite with code generated by the TypeScript compiler.

For now, define a new entry file at src/http/get-index/index.ts

// src/http/get-index/index.ts

export async function handler(req: object) {
  return {
    body: JSON.stringify({ok: true})
  }
}

View source

Notice: we’re using TypeScript syntax!

Install TypeScript

TypeScript is extremely configurable and can be extended for many use cases with relative ease. First install it:

npm i typescript

Configure TypeScript

The final boss (already)! We need to configure TypeScript to transpile entry.ts into index.js. This way both local dev and live deployment will work as we’d expect them to. Create tsconf.json in the project root:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true
  },
  "files": [
    "./src/http/get-index/index.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

View source

We won’t dig into the config too much, but you’re certainly welcome to! Suffice to say, this will generate a CommonJS module that AWS Lambda can run.

Configure npm scripts

Add the classic npm start and npm run build commands:

"scripts": {
    "build": "npx tsc",
    "start": "npm run build && npx arc sandbox",
    "deploy": "npm run build && npx arc deploy"
  },

Work locally, then deploy to AWS when you’re happy with your app

Set up CI/CD

arc27.png

Now that everything is working locally we can set up Begin to deploy our code from GitHub whenever we commit. Login to Begin with your GitHub account, click New app, and scroll to the big Import app button. (My first build was completed in 11.003 seconds!)

You can use the GitHub repo brianleroux/arc-example-typescript to get started.

That’s it!

Now you’re up and running with serverless TypeScript.

arc27.png

async function handler (req: object) {} returns the above!

You can find the full source code for this tutorial here.

Next steps