KINDERAS.COM

Optimizing your AWS Lambda bundle size - Quicktip

When working with Node.js on AWS Lambda there are some limits one should be aware of. One of these concerns the bundle size, in other words the total file size of your code folder running on the Lambda function. Currently your code bundle must be below 250 MB (unzipped, including layers).

The notorious «node_modules» folder might cause you some grievance in the bundle size departement. Especially if you’re importing the aws-sdk and/or other humongous dependencies. However, there is one really simple method you can use to minimize the size of the «node_modules» folder.

In two steps

  1. Move all the dependencies not needed for actually executing the code* to either «devDependencies» or «optionalDependencies». This might be things like TypeScript, testing frameworks, serverless and so on.
  2. When you build for deploy, install dependencies using «npm install —only=prod —no-optional». This will skip all those dependencies you moved in step 1.
  3. Watch your «node_modules» folder shrink in size

(*) Node.js projects often contain dependencies used for building and testing the project during development. Packages like TypeScript, Jest, Mocha, Serverless are usually not needed when the code is running in the AWS Lambda environment. Hence the code for such dependencies will just add unnecessary bytes to the bundle size and should be omitted from the production bundle.

Carry on.