Webpack 5 and Typescript with Serverless framework
Quick tutorial on configuring webpack and typescript
Pre req: I hope you have NodeJs
and serverless
installed and configured. (Check this video if you haven’t. https://www.youtube.com/watch?v=NjZaXwNU08Q)
Initialising a new Serverless project: Run sls create -t aws-nodejs -p sls-server
to create a new project. This will make use of aws-nodejs
template to get us started.
Install dev dependancies: Run yarn add -D webpack serverless-webpack typescript ts-loader
This will create a package.json
file, yarn.lock
file and install dev dependancies.
Add tsconfig.json: Since we intend to use typescript, we need a tsconfig.json
file with our typescript configuration. I have my configuration file on a gist. Feel free to use it. Add that to your root directory. (Your code editor might show an error because we don’t have a src
folder) https://gist.github.com/harshq/c9abe4d5c1c8641492cad3600c7c235f
Add webpack.config.js: Webpack needs a configuration file to work. I have a bare bone config that has ts-loader
for typescript here. Add that to your root directory too.
https://gist.github.com/harshq/df1e25b12de12365d03da5c18d754480
Create your app folder: Create a src
directory in your app folder. This is where you will have your .ts
files. Rename your handler.js
file to handler.ts
and move it inside the src
folder. (You will have change your handler by adding any
type to event
object. Check the screenshot below)
Finally, we need to make some changes in our serverless.yml
file. Heres my configuration in a gist. I’ve also added some comments there. https://gist.github.com/harshq/2ec43934c51484fbb2ee2d6755046966
Now you can run sls webpack
to build your project.
You’ll notice that it creates a new folder in your root directory called .webpack
. It should have separate bundles for your functions. (Don’t forget to include this folder in your .gitignore)
Your serverless setup now uses webpack 5 and typescript. Happy coding!