Using TypeScript with AWS SAM Local
In a world where scalability is everything it is hard to ignore the new wave of “Serverless”. One of the biggest players in this space is Amazon AWS with their Lambda offering.
In this post I am going to try and explain how I set up my AWS Sam projects using Webpack and TypeScript.
The thought behind my approach is to make the CodeUri
part of my template
point to the Webpack output. Then have Webpack running in “watch” mode in order to recompile when i save a file. This adds the requirement of having Webpack running in the background, which is somewhat a pain. It also requires some manipulation of the entries file. In order to have sam package
not include a whole lot of useless files.
Dependencies
First we need a lot of dependencies (it is Node after all).
Install the following dependencies with Yarn or NPM:
yaml-cfn
Can parse a CloudFormation template file. We need this to extract the functions to get the output path for Webpackwebpack
….typescript
….ts-loader
….
Webpack Configuration
The configuration above looks through the template.yml
file that AWS Sam uses and looks for AWS::Serverless::Function
resources. Then it filters out the non nodejs
ones. Since we only want to do this for the Node functions. It then takes the handle like index.handler
removes the “.” and appends .js
to the `index` part. Also it takes the CodeUri
and prepends it to the handler.
The Example
Using the above Webpack configuration and the following AWS SAM Template:
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'Resources:
MyFunction:
Type: 'AWS::Serverless::Function'
Properties:
Handler: index.handler
Runtime: nodejs10.x
CodeUri: .webpack/packages/my-function
It will then produce the following entries for Webpack to compile:
{
'packages/my-function/index': 'packages/my-function/index.ts'
}
Then you can run webpack --watch
and use aws local sam invoke -e <myEvent.json>
as normal.
Happy Coding!