35
Lightning fast & simple Typescript Serverless builds
Slow builds tend to cost more than just the time they waste. More than a few seconds and you're off checking Slack and all of a sudden it's been a few minutes. Any longer and all of a sudden you've been on Reddit for 20 minutes. Having a fast build means you've got a faster feedback loop and less risk of having to context switch due to getting distracted.
Let's start in an empty folder by running npm init -y
to initialize a new project. Next, we create a function that will act as our Lambda handler, in src/function.ts
:
// src/function.ts
export const handler = async (event) => {
console.log(event);
return {
status: 200
};
};
Now since we'll be using Serverless and esbuild to package and deploy our app, we'll need to install Serverless and the Serverless esbuild plugin: npm install serverless serverless-esbuild --save-dev
Finally, to deploy our app all we need to do is create a serverless.yml
# serverless.yml
service: esbuild-demo
plugins:
- serverless-esbuild
provider:
name: aws
runtime: nodejs14.x
functions:
function:
handler: src/function.handler
and now we can run npx serverless deploy
to get our app up and running in AWS - transpiled, three shaken & ready to rock. No additional configuration is necessary but you can of course choose to configure esbuilds behavior if needed. The transpile target is chosen automatically from the Lambda runtime from the Serverless provider setting, but it will also automatically discover and respect tsconfig.json
if you have it.
Setting up unit testing with Jest is almost just as simple. First, we need to add Jest, Jest types, and the Jest esbuild transformer:
npm install jest esbuild-jest @types/jest --save-dev
and then configure Jest to use the esbuild transformer:
// jest.config.json
{
"transform": {
"^.+\\.(j|t)sx?$": "esbuild-jest"
}
}
We can now also write Typescript unit tests:
// tests/function.test.ts
import { handler } from '../src/function';
describe('[function]', () => {
it('should return status 200', async () => {
const res = await handler(null)
expect(res).toEqual({
status: 200
});
});
});
and run them with npx jest
!
Having migrated a few more or less complicated projects from Webpack setups, esbuild tend to "just work" every time as a drop-in replacement. It provides significantly faster builds all while requiring a fraction of the config! 🚀
You can find the complete demo project here!
If you enjoyed this post and want to see more, follow me on Twitter at @TastefulElk where I frequently write about serverless tech, AWS, and developer productivity!
35