Intro
TypeScript is a programming language which adds types to JavaScript. It allows to avoid many issues and find compilation errors beforehand. By using it you can definitely make your code much more readable, reliable and simplify your life (save a lot of your nerve cells). It can be used whenever you need to write JavaScript application and it is totally suitable to write code for AWS lambda. This article is about steps needed to write your aws lambda using TypeScript.
Steps to use TypeScript in aws lambda
Initiate aws lambda structure using SAM
SAM
stands for Serverless Application Model and it’s an open source framework for building serverless applications
(SAM github). We will use it for current example.
The following command will start initiating our lambda.
Settings are pretty straightforward, but just in case you need them:
As a result the following structure will be created;
Convert JavaScript into TypeScript
As you can see we have app.js
file which contains actual code of initiated lambda function:
To convert JavaScript lambda into TypeScript lambda we need:
Step 1. Update package.json file
Add TypeScript compile
script and needed devDependencies (@types/aws-lambda, @types/node, typescript
) to package.json
Step 2. Create tsconfig.json (TypeScript configuration file)
Where:
module
- allows to use different modularization options. In this caseCommonJS
is used because aws runtime environment understands it without additional settings see docsmoduleResolution
- defines strategy to locate modules.classic
strategy did not work, that’s whynode
is used see docsoutDir
- output directory where javascript files will eventually end uptarget
- specifies which language features will stay in output files see docs
Step 3. Convert js files into ts files
Apart from changing extension we will also change implementation to start using types
Now let’s check that everything compiles into JavaScript by running the following command
According to tsconfig.json
file, our javascript files should appear in build folder.
Step 4. Update template.yaml file with new path to source code
Right now we need to let SAM
know where to look for our JavaScript files, that’s why we need to update template.yaml
NOTE: Be aware that Handler
property has to point to app.js file and function in it. If you named that function differently, you need to change this field correspondingly.
Deploy lambda and check it
SAM
will need correct AWS credentials to execute deployment.
To check your lambda you can find your API gateway url in aws console or just check your output from sam deploy
command.
Conclusion
TypeScript usage in aws lambda is very simple, but brings a lot of benefits to our developer’s life.
In the next articles we will deploy TypeScript lambda using Serverless
framework and built in SAM
functionality